Laravel Eloquent: sum with groupBy

Document::groupBy(‘users_editor_id’) ->selectRaw(‘sum(no_of_pages) as sum, users_editor_id’) ->pluck(‘sum’,’users_editor_id’); // originally lists(), which was deprecated in favour of pluck in 5.2 // and dropped completely in 5.3 // ->lists(‘sum’,’users_editor_id’); // returns array like this: array( users_editor_id => sum, … ) Or this way (which I wouldn’t use, since it won’t be actual ORM result): Document::groupBy(‘users_editor_id’) ->selectRaw(‘*, sum(no_of_pages) as … Read more

how get random row laravel-5

These works but probably you didn’t use the right namespace, just use the use statement at the top of your class name like this: <?php namespace SomeNamespace; use App\Quotation; // Says “Quotation.php” is in “App” folder (By default in L-5.0) class someClass { //… } Then you may use in your method something like this: … Read more

Order by relationship column

join() worked fine thanks to @rypskar comment $items = UserItems ::where(‘user_id’,’=’,$this->id) ->where(‘quantity’,’>’,0) ->join(‘items’, ‘items.id’, ‘=’, ‘user_items.item_id’) ->orderBy(‘items.type’) ->select(‘user_items.*’) //see PS: ->get(); PS: To avoid the id attribute (or any shared name attribute between the two tables) to overlap and resulting in the wrong value, you should specify the select limit with select(‘user_items.*’).

How to define and use JSON data type in Eloquent?

In your migrations you can do something like: $table->json(‘field_name’); And in your model you add the field to the $casts property to instruct Eloquent to deserialize it from JSON into a PHP array: class SomeModel extends Model { protected $casts = [ ‘field_name’ => ‘array’ ]; } Source: https://laravel.com/docs/5.1/eloquent-mutators#attribute-casting Note: This is also relevant answer … Read more