I am following a Laravel course on Udemy and while I followed everything the instructor did, for some weird reason I am not getting the expected result.
This is the Relationship One to One lesson and I added a function in User Model to check if it has any posts.
Then added the route to display post if user_id equals.
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Http\routes.php
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post;
});
Below is the screenshot from the database showing that I have a post with user_id = 1 in the posts table. I also have a user with id=1 in the user's table. MySQL data Why do I get a blank page when visiting domain/user/1/post?
Sohel, i got a result from your function, but had to use
var_dump(User::with('post')->where('id',1)->first());
Then tried something else:
return User::with('post')->where('id',$id)->first();
And this is the result:
{"id":1,"name":"Nick","email":"[email protected]","created_at":"2018-03-15 09:49:51","updated_at":"2018-03-15 09:49:51","post":null}
laravel.logfile for any errors? - N.B.return $this->hasOne('App\Post', 'post_id', 'id');. Also, enable error reporting if you want to see errors. - Ron van der Heijdendd(User::with('post')->where('id',1)->first())gives - Sohel0415