Ad

Laravel 5, Trying To Get Property Of Non-object

- 1 answer

My Controller :

 public function show($id){
    $user_id_1_connections = Connection::whereUser_id_1AndConnection_status($id, 1)->get();
    $user_id_2_connections = Connection::whereUser_id_2AndConnection_status($id, 1)->get();
    return view('connection.showConnection',['user_id_1_connections' => $user_id_1_connections, 'user_id_2_connections' => $user_id_2_connections]);
} 

My Model :

protected $table = 'connections';
protected $fillable = ['user_id_1','user_id_2','connection_status'];

public function user()
{
    return $this->belongsTo('App\User');
}

My Blade :

@foreach($user_id_1_connections as $user_id_1_connection)
{{ $user_id_1_connection->user->name }}
{{ $comment->user->name }}
@endforeach
@foreach($user_id_2_connections as $user_id_2_connection)
{{ $user_id_2_connection->user->name }}
@endforeach

I have made foreign key to user_id_1 and user_id_2 to users table.

$table->integer('user_id_1')->unsigned();
        $table->foreign('user_id_1')->references('id')->on('users')->onDelete('cascade');
        $table->integer('user_id_2')->unsigned();
        $table->foreign('user_id_2')->references('id')->on('users')->onDelete('cascade');

But when I'm running this code. It's showing the error : Trying to get property of non-object.

Ad

Answer

The problem here is probably that you don't have user assigned to each connection so instead of:

{{ $user_id_1_connection->user->name }}

you should write rather something like this:

{{ $user_id_1_connection->user ? $user_id_1_connection->user->name : 'unknown' }}

same in all other places when you use $x->y->z syntax. To display z you should make sure $x->y is not null

Ad
source: stackoverflow.com
Ad