I have a little problem but it's frustrating me a lot.
I have two tables
1. users
2. posts
The user can have many posts and the post belongs to one user
My question : how to get the first post when typing the relation?
public function index() {
$user = User::find(1);
// here it will return all posts
$user->with('posts');
return view('home.index',compact('user'));
}
By the way : i used closure but it didn't work ... it return all users with posts
public function index()
{
$user = User::find(1);
$user = $user->with(['posts' => function ($query) {
$query->first();
}])->get();
return $user ;
return view('home.index',compact('user'));
}
and the result is like that :
[
{
"id": 1,
"name": "Barney Walter",
"email": "wuckert.murphy@example.org",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 2,
"name": "Dr. Makenzie Rutherford",
"email": "estroman@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 3,
"name": "Ernesto Shanahan",
"email": "pwill@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 4,
"name": "Rosalinda Cartwright",
"email": "josefa.murazik@example.com",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": []
},
{
"id": 5,
"name": "Kyleigh Willms",
"email": "ddach@example.net",
"created_at": "2016-12-22 10:48:45",
"updated_at": "2016-12-22 10:48:45",
"posts": [
{
"id": 1,
"user_id": 5,
"name": "Malcolm Simonis",
"title": "Autem quidem quia earum ipsam. A a commodi id adipisci quia minima iste numquam. Eum eius odit porro veniam. Et iure occaecati sapiente minima et beatae. Labore eius labore accusamus sapiente sed eveniet accusamus.",
"is_published": 1,
"created_at": "2016-12-22 10:54:14",
"updated_at": "2016-12-22 10:54:14"
}
]
}
]
any help about that ... please !!