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?
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.
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 ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With