Posts

Showing posts with the label laravel

Multilevel relationship whereHas on eloquent Model in Laravel

Multilevel relationship whereHas on eloquent Model in Laravel I'd like to find Project::with('tasks.tags')->get(); Project::with('tasks.tags')->get(); where only projects with a particular id of tag return in the result set. For ex. I'd like to find a project with tasks and tasks with tags with only id of 1. In other words, filter the tasks return inside of the Project - Task relationship. I have tried various ways but have failed so far. I have tried: $project = Project::with('tasks.tags')->whereHas('tasks', function($query){ $query->whereHas('tags', function($query) { $query->where('id', 1); }); })->get(); And: $project = Project::with('tasks.tags')->whereHas('tasks', function($query){ $query->whereHas('tags', function($query) { $query->where('tag_id', 1); }); })->get(); This is how the re...

$(…).DataTable is not a function when using Laravel Mix

$(…).DataTable is not a function when using Laravel Mix I struggle using Laravel Mix and DataTables. The issue I have is that when I compile down my .js-files etc., each time I would then visit a page that would execute a jQuery datatable, the follwoing error is thrown: The error is: jQuery.Deferred exception: $(...).DataTable is not a function TypeError: $(...).DataTable is not a function Uncaught TypeError: $(...).DataTable is not a function From what I understand, $(...).DataTable is not a global variable, but how can I make sure that it is accessible "on a global scope" / within my app? $(...).DataTable The following is my setup: app.js import jquery from 'jquery/dist/jquery.slim' import 'bootstrap-sass' import 'datatables.net'; import dt from 'datatables.net-bs'; window.$ = window.jQuery = jquery; webpack.mix.js mix .js('resources/assets/admin/js/app.js', 'js/') .extract([ 'jquery', 'bootstrap-s...

Is there any other way to get Laravel to reload env variables?

Is there any other way to get Laravel to reload env variables? I have a shared hosting account on a well known host. I have my Laravel site uploaded and functioning for the most part. But I had to make an env change. Now I can't get Laravel to see the change. I know this is common issue. I have tried running the artisan commands to clear config and cache (php artisan config:cache & php artisan cache:clear ) but this fails with an error: Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home4/cmatthewc/cvbaptistapp/artisan on line 33 Is there any other way to get Laravel to refresh its cache from env? TY in advance... what version of laravel? Also, thats a PHP error in the artisan file, did you modify it? – Derek Jun 29 at 18:11 ...

laravel redirect back to post route, i get MethodNotAllowedHttpException

laravel redirect back to post route, i get MethodNotAllowedHttpException At first on a get request i show a form, on submitting it, it goes to a post url does some working in the controller and then returns another view which has a form. after submitting this form i validate some things and if the validation fails i want to redirect back with some errors but unfortunately laravel isn't allowing me to redirect back to a post method. Is there any way i can accomplish this? i have seen this answer on laracast https://laracasts.com/discuss/channels/laravel/redirect-back-to-post-route-i-get-methodnotallowed-exception but i couldn't grasp the recommendation these are my routes in the order described above. Route::get('/purchasePacks', 'masterDealerController@purchasePacks')->name('purchasePacks'); Route::post('/confirmPuchasedPacks','masterDealerController@confirmPuchasedPacks'); Route::post('/storeOrder','masterDealerCont...

How can I remove spaces in view?

How can I remove spaces in view? I use laravel 5.3 My case is like this : My code in view : " @if(isset($country)) {{ $country }} @endif @if(isset($city)) @if(isset($country)) - @endif {{ $city }} @endif " The result like this : " England - London " I want the result like this : "England - London" How can I do it? What's the difference between result and expectation ? Just spaces ? – Sagar Gautam Jun 7 '17 at 8:36 @Sagar, Yes, it just spaces – Success Man Jun 7 '17 at 8:36 Answer is here stackoverflow.com/questions/26146045/… – kRicha ...

Laravel: How to enable stacktrace error on PhpUnit

Laravel: How to enable stacktrace error on PhpUnit I have a fresh installation of laravel 5.4 I've tried to modify the default test just to see a failing test. tests/ExampleTest.php class ExampleTest extends TestCase { /** * A basic test example. * * @return void */ public function testBasicTest() { $response = $this->get('/ooops'); $response->assertStatus(200); } } I was expecting to see more detailed error like no route has been found or defined etc, but instead just this error saying no route has been found or defined Time: 1.13 seconds, Memory: 8.00MB There was 1 failure: 1) TestsFeatureExampleTest::testBasicTest Expected status code 200 but received 404. Failed asserting that false is true. /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:51 /var/www/tests/Feature/ExampleTest.php:21 Its really hard to do TDD without meaningful error (yeah I know 404 in this case is enough, bu...

composer dump-autoload do nothing

composer dump-autoload do nothing I am trying to execute the command composer dump-autoload on a Laravel project, but it does nothing. It only writes Generating optimized autoload files , then stops. composer dump-autoload Generating optimized autoload files I tried it on an other project, and it worked well (discovered packages, and so on). I also tried it after updating composer ( composer self-update ), after checking that my composer.json is right ( composer validate ). Nothing changed... composer self-update composer validate The command composer update works well on the update part, but does the same when it arrives to the dump-autoload one. composer update Does someone have a solution? Thanks! 1 Answer 1 Check your composer.json , pre-install-cmd and post-autoload-dump was missing. composer.json pre-install-cmd post-autoload-dump Your scripts should look like this scripts { "scr...

Dynamic form fields should not have same value in Laravel

Dynamic form fields should not have same value in Laravel I'm implementing a form with dynamic fields being added by an add field button. What I need is to prevent some of these fields to have the same value before submission. Currently my Request rules look like this: public function rules() { return [ 'myfield.*.domain' => 'required|url', 'myfield.*.group' => 'required', 'myfield.*.client' => 'nullable' ]; } For instance, what if want the domain input to be unique in the form submission (not the database)? Is this possible? Any help would be really appreciated! Thanks! EDIT Adding 'distinct' rule did the job for the specific field. 'myfield.*.domain' => 'required|url|distinct' The validation errors though sometimes don't show up at my view. Testing the same input errors on purpose, the error messages sometimes show up as they should and sometimes $errors->al...

Homestead: How to upgrade PHP version

Homestead: How to upgrade PHP version I installed a year ago Homestead with Laravel 5.5. Now I want to upgrade to Laravel 5.6. I upgraded Homestead as explained here with vagrant box update git pull origin master This forced me also to upgrade my vagrant to 2.1.2 . vagrant 2.1.2 Now when I log in with vagrant ssh vagrant ssh I cannot upgrade to Laravel 5.6, because when I run composer update I get this warning: composer update Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - This package requires php >=7.1.3 but your PHP version (7.0.27; Package overridden via config.platform (actual: 7.1.7)) does not satisfy that requirement. Problem 2 - laravel/framework v5.6.9 requires php ^7.1.3 -> your PHP version (7.1.7-1+ubuntu16.04.1+deb.sury.org+1) overridden by "config.platform.php" version (7.0.27) does not satisfy ...

Remove time() string from filenames in Laravel when showing

Remove time() string from filenames in Laravel when showing I am using time() function to add time string to the file names like this and storing them in the database $filename = time() . $file->getClientOriginalName(); But How Can I remove this string when I show the files to the user and when the user downloads the file. I am using Laravel by the way. 1 Answer 1 The timestamp is 10 digits I believe, so doing: substr($filename,10): Would trim it from the beginning of the filename. When downloading a file, you can give the file name which is displayed/suggested to the user like this: return response()->download($filename, substr($filename, 0, 10), $headers); substr($filename, 0, 10): this has removed the file name except the time() string but using this substr($filename, 10) has solved my problem. and I wanna ask how could I make users download the file. I mean how...

One post belonging to many businesses

Image
One post belonging to many businesses I have a database with a structure similar to the one below (apologies if the diagram isn't fully clear). The statistics, favourite_likes and category_links all have polymorphic relationships with the posts table. A business can have many posts, and a post can have many dates. The post will only appear on the frontend of the site if it has a date in the post dates table which is in the future. The issue is I need to change this design so that its possible for one post to be linked to many businesses, this seems fairly straightforward however there are many issues: Each post and business have a coords spatial column, this column is used for a nearest me search on the frontend of the website. The coords column is optional for the user in the backend if they don't enter anything the system will just copy the coords from the business. So if I have a post linking to many businesses then it will need to store more than one set of coordinates. Fu...

JSON return null 'meiter'

JSON return null 'meiter' I have a function that displays the select id 'technicien' and he showed his name from table user and there 'metier' techniciens_tables Schema::create('techniciens', function (Blueprint $table) { $table->increments('id'); $table->boolean('actif')->default(1); $table->float('moyenne_avis')->nullable(); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->datetime('deleted_at')->nullable(); $table->timestamps(); }); metier_tables Schema::create('metiers', function (Blueprint $table) { $table->increments('id'); $table->string('libelle_metier'); $table->datetime('deleted_at')->nullable(); $table->timestamps(); }); users_table Schema::create('users', function (Bl...

Laravel pluck with custom method from model

Laravel pluck with custom method from model I'm using Laravel 5.6 . I have a users table and firstname and lastname fields. 5.6 users firstname lastname In my User model I also have this function User public function name() { return $this->firstname . ' ' . $this->lastname; } And now in another controller, I want to create a dropdown menu with all the users. But I would like to display the name() and not only the first/lastname. name() I'm currently using this $users = AppUser::pluck('lastname', 'id'); return view('myview', compact('MY_collection' , 'users')); And in my view (with collective/html) {!! Form::select('user', $users, isset($user) ? $MY_collection->user: null, ['class' => 'form-control']) !!} Is is possible to use pluck with a method function ? Or should I do something else? I am also aware of the accessor solution but I don't have a name attribute in the databa...

publish a post only if the required fields are stored in db

publish a post only if the required fields are stored in db I have a link to publish a post that is in draft status (stats = 'D' in posts table): <a href="{{route('posts.publish', ['id' => $post->id])}}">Publish</a> I created a route for this link: Route::get('post/{id}/publish', [ 'uses' => 'PostsController@publish', 'as'=>'posts.publish']); When the link "Publish" the code goes to the PostsController publish(). In this method is necessary to verify if all mandatory fields for a post be published are not null. If they are null the post should not be published, it should appear a message informing the user that the required fields (name, categories, image, content, etc) needs to be introduced before the post be published. Otherwise the post should be published, that is the status should be updated from "D" to "P". Do you know how to achieve that? Is necessary ...

Dates 20 years in the future considered invalid

Dates 20 years in the future considered invalid Laravel validator doesn't accept dates that are more than 20 years in the future: Route::get('test', function() { $input = ['date' => '2039-01-01']; $rule = ['date' => 'date']; $v = IlluminateSupportFacadesValidator::make($input, $rule); return 'Fails: '.$v->fails(); }); The following example returns true, despite the fact that the date is correct. But when I change 2039 to 2037, it works. How can I do to make the validator always return false? Check this: stackoverflow.com/questions/3953333/maximum-time-php – Mayank Pandeyz Jun 29 at 10:03 I see there will be a problem in 2038, but its there a way to bypass this limit for the validation as I'm using dates and not UNIX timestamps? ...

Laravel pagination append data in one variable and other in another variable

Laravel pagination append data in one variable and other in another variable I am facing a problem in laravel pagination. In laravel when I called paginate() method it returns paginate() { "total": 50, "per_page": 15, "current_page": 1, "last_page": 4, "first_page_url": "http://laravel.app?page=1", "last_page_url": "http://laravel.app?page=4", "next_page_url": "http://laravel.app?page=2", "prev_page_url": null, "path": "http://laravel.app", "from": 1, "to": 15, "data":[ { // Result Object }, { // Result Object } ] } This type of Object. What I want is that I want to set data in one vairable for example $a and except data all other value in $b . $a $b But when I added appends('data') of my paginate variable it did not working...

Laravel/SQL: How to fetch data from multiple table in a single query? that too using 'where'

Laravel/SQL: How to fetch data from multiple table in a single query? that too using 'where' Working on a search functionality on Laravel App(Blog/Posts). There are multiple types of posts (each having a separate table in the database) Like Business posts, Social Life posts etc.. Below is the search function on SearchController class SearchController extends Controller { public function search(Request $request, $query = null) { if($query == null) return redirect()->route('home'); $search = Business::where([['title','like','%'.$query.'%'],['status','=',1]]) ->orWhere([['description','like','%'.$query.'%'],['status','=',1]]) ->paginate(10); return view('front.search',[ 'results' => $search, 'query' => $query ]); } } So basically ...