Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic eager loading?

Rather than doing something like this (which I do dozens of times across the site):

$posts = Post::with('user')
    ->with('image')
    ->get();

Is it possible to automatically call with('image') whenever with('user') is called? So in the end, I could do just:

$posts = Post::with('user')
    ->get();

And still eager load image?


2 Answers

Add the following in your model:

protected $with = array('image');

and that should do the trick.

The $with attribute lists relations that should be eagerly loaded with every query.

like image 170
jedrzej.kurylo Avatar answered Nov 03 '25 11:11

jedrzej.kurylo


Here another solution that works like a charm !

class Post extends Model {

    protected $table = 'posts';
    protected $fillable = [ ... ];

    protected $hidden = array('created_at','updated_at');

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function userImage()
    {
        return $this->belongsTo('App\Models\User')->with('image');
    }

}

$posts = Post::with('userImage')->get();

Using this you can still use your user posts $posts = Post::with('user')->get(); whenever you don't want to make an additional call to retrieve images ..

like image 32
Mohamed Salem Lamiri Avatar answered Nov 03 '25 09:11

Mohamed Salem Lamiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!