Skip to content
Advertisement

Laravel Call to undefined method HasMany::mapInto() when requesting data

I am getting a strange error which I cannot work out.

I have a User and also a Partner model. A user can have multiple partners. I am trying to retrieve a list of partners that the user has. I am also using Laravel Sanctum as my auth guard.

My relationship code is as follows;

In my user model

public function partners(): HasMany
{
    return $this->hasMany(Partner::class);
}

In my Partner model

public function user(): BelongsTo
{
    return $this->belongsTo(User::class);
}

My route definition looks like so;

Route::middleware(['auth:sanctum'])->group(function () {
    Route::apiResource('partners', ApiPartnerPartnerController::class)
    ->only(['index']);
});

and finally in my controller;

public function index(Request $request)
{
    return PartnerResource::collection($request->user()->partners());
}

When I hit the endpoint though, I am getting the following error;

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::mapInto()

I cant figure out the issue. Any insight would be greatly appreciated.

Advertisement

Answer

When You are Calling user()->partners() it returns IlluminateDatabaseEloquentRelationsHasMany Instance.

Resource needs to get IlluminateDatabaseEloquentCollection Instance.

You have to just call user()->partners ( Remove parenthesis )

Or call get method on IlluminateDatabaseEloquentRelationsHasMany Instance, to get Collection

user()->partners()->get()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement