Automatic download?

Instead of doing something like this (which I do dozens of times throughout the site):

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

      

Can I automatically call with('image')

on call with('user')

? So in the end I could only do:

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

      

And still an impatient loading image

?

+3


source to share


2 answers


Add to your model:

protected $with = array('image');

      



and that should do the trick.

The $ c attribute lists the relationships to be loaded with each request.

+3


source


Here's 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 messages $posts = Post::with('user')->get();

when you don't want to make an extra call to fetch images.

+1


source







All Articles