I
I
Ilya Loopashko2021-03-25 07:43:03
Laravel
Ilya Loopashko, 2021-03-25 07:43:03

How to output value from two joined tables?

Kind.

There are two tables, user and post. I need to display user with posts from post that belong to him.

User table
id: 1
name: Alex

id: 2
name: Ilya

Post table
id: 1
title: Good News
user_id: 1

id: 2
title: Very good news
user_id: 2

id: 3
title: Not bad good news
user_id: 2

Result :
Alex
Good News

Ilya
Very good news
Not bad good news

Post model:

public function user()
    {
        return $this->belongsTo(User::class);
    }


user model:
public function posts()
    {
        return $this->hasMany(Post::class, 'user_id', 'id');
    }


controller
$users = User::with('posts')->get();
        $posts = Post::with('user')->get();
        return view('index', compact('users', 'posts'));


view:
@foreach ($users as $user)
    <h3>{{ $user->name}}</h3>
        @foreach ($posts as $post)
            <p>{{ $post->title }}</p>
        @endforeach
@endforeach

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kudrya, 2021-03-25
@Mugenzo

$user->posts

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question