Zul K Zul K - 1 month ago 5
PHP Question

how to access my post class with one to one relationship in laravel

I am new in Laravel. I have two classes(User,Post) and I want to call Post class from User class by using one to one relationship, hasOne(namespace).is it possible?It is same as below link video but code is different.


here is my User class


namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Post;

class User extends Authenticatable

protected $fillable = [
'name', 'email', 'password',

protected $hidden = [
'password', 'remember_token',

public function post(){
return $this->hasOne('App\Post');

This is routes.php

Route::get('/user/{id}/post',function ($id){
return User::find($id)->post->content;


my Post class


namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
use SoftDeletes;

protected $dates=['deleted_at'];
protected $fillable=[

here i called get method using User class and i want to retrieve posts table content column (which is from Post class)
i want know how to do because i run this code i got an error
at HandleExceptions->handleError('8', 'Trying to get property of non-object', 'C:\xampp\htdocs\cms\app\Http\routes.php', '144', array('id' => '1')) in routes.php line 144
here is tables
enter image description here

enter image description here

enter image description here


We would have to see Post class to be sure, but my guess is that the tables are simply empty. The user has no posts, so User::find($id)->post is null, and then you try to get content property of it, which results in an error you got, as null is literally non-object :). Just generate some sample data to check if that's true.

Also, returning an object like that will not work:

// this will not work
return User::find($id)->post->content;

// do this in the testing phase to see if relationship works
return print_r(User::find($id)->post->content, true);
// or

Otherwise you seem to be on the right track, keep going!