'trying to get property 'sector' of non-object

guys. I'm trying to pass the 'officeToSector' id from employee table to get the 'sector' table values using the id. But it doesn't work, it show me 'trying to get property 'sector' of non-object'. However, if I entered a number like 1 or 2, I can access the property. I had checked the type of the return query, it is an object not an array...

Can you guys pls help me to find out what is the problem. Thank you very much.

$employees = $this->employeeRepository->listEmployees();

return Datatables::of($employees)
                ->addColumn('department', function($employee){
                           // if I assign 2 to $id, I got the return value, 
                           // but it I use the emp->dept_id, I get the non-object error
                           $id = (int)$employee->department_id; 
                           $sector = OfficeToSector::find($id);
                           return $sector->sector->name;
                )}
                ->rawColumns(['department'])
                ->make(true);

enter image description here

officeToSector model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

// use Illuminate\Database\Eloquent\Relations\Pivot;

class OfficeToSector extends Model
{
    protected $table = 'office_to_sectors';
    /**
     * @var array
     */
    protected $fillable = ['office_id','sector_id'];

    public function office()
    {
        return $this->belongsTo(Office::class, 'office_id', 'id');
    }

    public function sector()
    {
        return $this->belongsTo(Sector::class, 'sector_id');
    }

    public function employee()
    {
        return $this->hasMany(Employee::class, 'employee_id', 'id');
    }

    public function registeredDepartment()
    {
        return $this->hasOne(DepartmentContent::class, 'department_id');
    }
}

sector model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Sector extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['name','status'];

    /**
     * @var array
     */
    protected $casts = [
        'status'    =>  'boolean',
    ];



    public function offices()
    {
        return $this->belongsToMany('App\Models\Office', 'office_to_sectors')->withPivot('sector_id', 'office_id')->withTimestamps();
    }

}


Solution 1:[1]

I found the solution. It is because one of the sector value in the officeToSector table is null. So, this is why Yajra Datatable cannot display the data because the table has null value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy Caney