Laravel Eloquent Relationships: Lesson 5 of 7

One to Many in View

Up Next

Many to Many

Autoplaying in 7 seconds!

Cancel

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 }}
@endforeach

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

Table of Contents

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

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.