I have a basic laravel 9 crud app.
There I have two tables in my db. companies and employees.
I’m trying to display single-user details on my employees.show blade
All my data is displayed correctly but when I try to print user’s company, I’m kept getting the following error.
Property [company] does not exist on the Eloquent builder instance.
Following is my employee model
protected $fillable = [
'first_name', 'last_name', 'email', 'phone', 'company_id'
];
public function company()
{
return $this->belongsTo(Company::class);
}
and the following is the show function in my controller
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id);
return view('employees.show', compact('employee','data'));
}
and this is my show.blade
<div class="row mb-4">
<label class="col-sm-2 col-label-form"><b>Company</b></label>
<div class="col-sm-10">
{{ $data->company->name }}
</div>
</div>
How can I display the company properly…
I have company_id as a foreign key in my employees’ table…
I have following when I dd $data
2
Answers
You’re returning a QueryBuilder from the
Employee
query in yourshow()
function. You want to add->get()
to return acollection
orEmployee
records:I think the problem in Query for get data. In employees.show you only show one data then and in controller you got collection of data as array. So your single data element can’t access because it is array and for execution you need to add foreach loop for that.
Here you need to change query method from
get()
tofirst()
and it will resolve your issue.Your show function code looks like this
Your employees.show blade looks like this