Laravel Eloquent Relationships

One to Many in View

We can call up the relationships in our controller. Let's say we wanted to grab all the posts from a user:

// load a users posts
$user  = $user->load('posts');
$posts = $user->posts;

// return a view with the user and posts
return view('profile', compact('user', 'posts'));

Then we can loop over those in our view:

@foreach ($posts as $post)
    The post title is {{ $post->title }}

Alternatively, you could skip grabbing the posts directly and call it via the relationship in the view:

@foreach ($user->posts as $post)
    The post title is {{ $post->title }}

Like this article? Follow @chrisoncode on Twitter