Добрый.
Есть две таблицы, user и post. мне надо вывести user с записями из post которые принадлежат ему.
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
Результат:
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