Eloquent Parent-Child relationship on same model

You should use with(‘children’) in the children relation and with(‘parent’) in the parent relations. For your code to be recursive: public function parent() { return $this->belongsTo(‘App\CourseModule’,’parent_id’)->where(‘parent_id’,0)->with(‘parent’); } public function children() { return $this->hasMany(‘App\CourseModule’,’parent_id’)->with(‘children’); } Note: Make sure your code has some or the other exit conditions otherwise it will end up in a never ending … 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

How to access model hasMany Relation with where condition?

I think that this is the correct way: class Game extends Eloquent { // many more stuff here // relation without any constraints …works fine public function videos() { return $this->hasMany(‘Video’); } // results in a “problem”, se examples below public function available_videos() { return $this->videos()->where(‘available’,’=’, 1); } } And then you’ll have to $game … Read more

laravel collection to array

You can use toArray() of eloquent as below. The toArray method converts the collection into a plain PHP array. If the collection’s values are Eloquent models, the models will also be converted to arrays $comments_collection = $post->comments()->get()->toArray() From Laravel Docs: toArray also converts all of the collection’s nested objects that are an instance of Arrayable … Read more