I am trying to show one single record based on id. And I am getting this error:
Trying to get property of non-object
Show function from ClientsController:
public function show( Clients $clients)
{
$clients = Clients::find($clients->id);
return view('clients.show', ['clients' => $clients]);
}
single show.blade view file
@extends('layouts.app')
@section('content')
<h1>{{ $clients->name }}</h1>
@endsection
Clients model:
class Clients extends Model
{
//
protected $fillable = [
'name', 'type', 'user_id', 'sales_id', 'regions_id'
];
public function user(){
return $this->belongsTo('App\User');
}
public function region(){
return $this->belongsTo('App\Regions');
}
public function sales(){
return $this->belongsTo('App\Sales');
}
}
Database: https://take.ms/7kuo4
You should correct your model binding using the singular for the type hinted variable name, i.e.:
public function show( Clients $client)
{
return view('clients.show', ['clients' => $client]);
}
The client for the client id that you're looking for is not being found. It appears that the route/model binding might not be configured correctly or you are not receiving the proper id from the request.
If route/model binding were working correctly and if the passed in id were found then you shouldn't have to make the find()
call.
$clients = Clients::find($clients->id);
The error in the blade template is because you are trying to access a property on a null value/a value that is not an object.
$clients->name
You can just use a null coalescing operator to handle the case if an object does not exist:
$clients->name ?? "No Name"