analogsnow's avatar

Accessing multiple models in one request.

Hello Laracast Community.

I am in the process of learning Laravel and I love it so far, but maybe I am trying to do things that I am obviously not ready for.... so here I am:

I have the following models and relationships:

  • Article::class (assuming that one article has many images, belongs to a profile, belongs to a category)
  • Image::class (belongsTo article)
  • Profile::class (has many articls, belongs to a user)
  • User::class (has a profile)
  • Category::class (has many articles)

Now, if I want to pass all available data to a view, such as:

-- Title, description from the article -- Images from the image model -- Country (from the profile model) -- Name from the User model -- Category (so i can build breadcrumbs)

I am doing something like, trying to load everything into one go.

 $Article = Article::where('status', 1)
     ->with('category')
     ->with('images')
     ->with('profile')         
     ->findOrFail($id);  

return view('article-view', $Article)

That works, but how do I also pull the User from the user model in the same request above?

The only way it works is to try:

$user = $Article->profile->getuserinfo;

where getuserinfo is a function in the Profile model with a relationship set to "Belongsto" User::class).

I hope that this makes sense.

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122
 $article = Article::where('status', 1)
     ->with('category', 'images', 'profile.user')         
     ->findOrFail($id);  

A few things to note here

  • your variables should always be lowercase. Save Uppercase for proper class name
  • you can load multiple relations with a single with statement
  • assuming profile has a user relationship you can load them both at once so you can access in the view like $article->profile->user->name for instance

If there is no such relationship;

 $article = Article::where('status', 1)
     ->with('category', 'images', 'profile')         
     ->findOrFail($id);  

  $user = $article->profile->getuserinfo;

You can then pass both through to the view with compact('article','user')

Please or to participate in this conversation.