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 >
<label ><b>Company</b></label>
<div >
{{ $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
CodePudding user response:
You're returning a QueryBuilder from the Employee
query in your show()
function. You want to add ->get()
to return a collection
or Employee
records:
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id)->get();
return view('employees.show', compact('employee','data'));
}
CodePudding user response:
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()
to first()
and it will resolve your issue.
Your show function code looks like this
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id)->first();
return view('employees.show', compact('employee','data'));
}
Your employees.show blade looks like this
<div >
<label ><b>Company</b></label>
<div >
{{ $data->company->name }}
</div>
</div>