Laravel Eloquent: How to order results of related models?

You have a few ways of achieving this: // when eager loading $school = School::with([‘students’ => function ($q) { $q->orderBy(‘whateverField’, ‘asc/desc’); }])->find($schoolId); // when lazy loading $school = School::find($schoolId); $school->load([‘students’ => function ($q) { $q->orderBy(‘whateverField’, ‘asc/desc’); }]); // or on the collection $school = School::find($schoolId); // asc $school->students->sortBy(‘whateverProperty’); // desc $school->students->sortByDesc(‘whateverProperty’); // or querying students … Read more

laravel eloquent relationship with and where clause based on foreign column

You may try this: $value=”someName”; Project::with([‘clients’, ‘tasks’, ‘status’ => function($q) use($value) { // Query the name field in status table $q->where(‘name’, ‘=’, $value); // ‘=’ is optional }]) ->where(‘status_id’, ‘!=’, ‘2’) ->whereUserId(Auth::user()->id) ->get(); Also you may try this (It will fetch records only if the query returns name you want, otherwise none): $value=”someName”; Project::with([‘clients’, ‘tasks’, … Read more

Laravel $q->where() between dates

You can chain your wheres directly, without function(q). There’s also a nice date handling package in laravel, called Carbon. So you could do something like: $projects = Project::where(‘recur_at’, ‘>’, Carbon::now()) ->where(‘recur_at’, ‘<‘, Carbon::now()->addWeek()) ->where(‘status’, ‘<‘, 5) ->where(‘recur_cancelled’, ‘=’, 0) ->get(); Just make sure you require Carbon in composer and you’re using Carbon namespace (use Carbon\Carbon;) … Read more

Laravel Eloquent sort by relation table column

Eager loading uses separate queries so you need join for this: $products = Shop\Product::join(‘shop_products_options as po’, ‘po.product_id’, ‘=’, ‘products.id’) ->orderBy(‘po.pinned’, ‘desc’) ->select(‘products.*’) // just to avoid fetching anything from joined table ->with(‘options’) // if you need options data anyway ->paginate(5); SELECT clause is there in order to not appending joined columns to your Product model. … Read more

What is the syntax for sorting an Eloquent collection by multiple columns?

sortBy() takes a closure, allowing you to provide a single value that should be used for sorting comparisons, but you can make it a composite by concatenating several properties together $posts = $posts->sortBy(function($post) { return sprintf(‘%-12s%s’, $post->column1, $post->column2); }); If you need the sortBy against multiple columns, you probably need to space pad them to … Read more

Create Models from database in Laravel

Warning, you may end up overwriting your JetStream or any other scaffolding models. take backup of them before overwriting them. If you are using MySQL and Laravel 5.1 or above you can use php artisan code:models from this package: reliese/laravel. All you need to do is: composer require reliese/laravel Add the service provider to your … Read more