Answer the question
In order to leave comments, you need to log in
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);
}
public function posts()
{
return $this->hasMany(Post::class, 'user_id', 'id');
}
$users = User::with('posts')->get();
$posts = Post::with('user')->get();
return view('index', compact('users', 'posts'));
@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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question