skip to Main Content

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

enter image description here

enter image description here

2

Answers


  1. 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'));
    }
    
    Login or Signup to reply.
  2. 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 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search