user4454001
user4454001

Reputation:

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?

Upvotes: 4

Views: 407

Answers (2)

Mohamed Salem Lamiri
Mohamed Salem Lamiri

Reputation: 6077

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 ..

Upvotes: 1

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

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.

Upvotes: 5

Related Questions