Search code examples
phplaravellaravel-5.7laravel-paginationlaravel-resource

Using pagination in Eloquent resource throws Undefined Property $id error in Laravel


I'm trying to build a application in Laravel 5.7 where I am having a model named CompanyBehaviour:

protected $table = 'company_behaviour';

protected $guarded= [];

public function companies()
{
    return $this->belongsTo('Noetic\Plugins\Conxn\Models\Company','company_id','id');
}

public function companyRole()
{
    return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_role_id', 'id');
}

public function companySpecialisation()
{
    return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_specialisation_id', 'id');
}

I'm having a resource file for this:

class CompanyBehaviourResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => $this->company->name,
            'company_role' => $this->companyRole->name,
            'company_specialisation' => $this->companySpecialisation->name,
        ];
    }
}

Which I need to use while fetching the data in my controller:

public function index(Request $request)
{

    return new CompanyBehaviourResource(CompanyBehaviour::whereHas('companies', function ($q) use($request) {
        $q->where('name', 'like', '%'.$request->search.'%');
    })->orderBy('created_at', 'desc')
        ->paginate(20)
    );
}

But when I called this I'm getting pagination error:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id

And the trace represents that:

class: "Illuminate\Http\Resources\Json\JsonResource"
file: "D:\~Resource\CompanyBehaviourResource.php"
function: "__get"
line: 17
type: "->"

Stating the 'id' => $this->id, this line. I've gone through the documentation of Laravel Resource API I'm couldn't find where I'm doing wrong. Help me out with this. Thanks.


Solution

  • Your call returns eloquent collection, instead of single result, thus not holding $id property. You should call collection method instead:

    public function index(Request $request)
    {
    
        return new CompanyBehaviourResource::collection(CompanyBehaviour::whereHas('companies', function ($q) use($request) {
            $q->where('name', 'like', '%'.$request->search.'%');
        })->orderBy('created_at', 'desc')
            ->paginate(20)
        );
    }