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

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', Api\Partner\PartnerController::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.

When You are Calling user()->partners() it returns Illuminate\Database\Eloquent\Relations\HasMany Instance.
Resource needs to get Illuminate\Database\Eloquent\Collection Instance.
You have to just call user()->partners ( Remove parenthesis )
Or call get method on Illuminate\Database\Eloquent\Relations\HasMany Instance, to get Collection
user()->partners()->get()

Related

Call to a member function givePermissionTo() on null

I'm trying to learn Spatie Laravel Permission Package. When trying to insert data to models has permissions table it gives the below error in postman. I don't know clearly how to insert data. I used the guide of spatie documentation.
error,
Call to a member function givePermissionTo() on null
here is my controller function
public function models()
{
Role::create(['name'=>'writer']);
Permission::create(['name'=>'edit post']);
Auth::id()->givePermissionTo('edit articles');
return 'hello';
}
I don't know if the question is clear enough. Please tell me if it's not clear.
Auth::id() return the id of the authenticated user, but you need to call givePermissionTo on a user object, not a user id.
try
Auth::user()->givePermissionTo('edit articles');
#brombeer was right. the issue was in the Auth::id() It says the authenticated user is not accessed in.
I changed my function line Auth::id()->givePermissionTo('edit articles'); to auth()->user()->givePermissionTo('edit articles');. Also the called __construct() function like this,
public function __construct()
{
$this->middleware('auth');
}
Then I accessed as an authorized user and inserted log in the token as a bearer token in postman. Then the issue was fixed.
Auth::id returns the id of the user. The method givePermissionTo should be called on an object of the user and not the id.
Here are two ways you can do it:
Method 1
Auth::user()->givePermissionTo('edit articles');
Method 2
$user = Auth::user();
$user->givePermissionTo('edit articles);

How to get instance of nested relationship in Laravel?

I have User model,
has many morph Notification. The Notification model also belongs to one NotificationType. I want to find data from NotificationType through the User instance. Here is the relationship code:
// User.php
public function notifications()
{
return $this->morphMany(Notification::class, 'notifiable');
}
// Notification.php
public function notification_type()
{
return $this->belongsTo(NotificationType::class, 'notification_type_id');
}
This is the code I have tried:
$notificationType = $user->notifications()->notification_type()->where('name', $this->data->type)->first();
But, it returns
staging.ERROR: Call to undefined method
Illuminate\Database\Eloquent\Relations\MorphMany::notification_type()
{"userId":"996cdaea-c6f3-444a-a430-036e1966ab91","exception":"[object]
(BadMethodCallException(code: 0): Call to undefined method
Illuminate\Database\Eloquent\Relations\MorphMany::notification_type()`
Is it possible to get the notification_type directly from the $user?
Thanks in advance!
Actually, I just found the solution. Since the $user->notifications() is the instance of Illuminate\Database\Eloquent\Relations\MorphMany, there is a function to get the instance of the Notification model, that is getRelated(). I found it here.
Since I got the Notification model class, I finally can retrieve the notification_type() relation method.
Here is my fixed code:
$notificationType = $user->notifications()->getRelated()->notification_type()->getRelated()->where('name', $this->data['type'])->first();
I am open to any suggestions to improve or fix the code above. Thank you.

Laravel - Get belongsTo relationship without id using Eloquent

i'm using laravel 7.30, I have a post model linked to user model with belongsTo relationship, I want to retrieve all posts with user property that contains only the name of the user for api purposes.
what i've tried so far.
public function index()
{
return Post::with('user:id,name')->get();
}
but the result of this code is a nested object 'user' which has 2 fields id and name on each post, I only want a single field with posts fields called user which has the name only and not a nested object for api purposes.
I've made it using database query builder, but i'm looking for a way using Eloquent
Thanks in advance
You can add this to your Post Model:
protected $appends = [
"author_name"
];
public function getAuthorNameAttribute()
{
return $this->user->name;
}
This will make sure the user's name is appended to the Post object every time it is being called.
Then from your controller, you can easily do this:
public function index()
{
return Post::get();
}

Find child model hasMany relation in laravel eloquent

Here is model structure of my Laravel 5.3 project,
User.php (Model)
it has one invitation method that returns the invitation of a user.
public function invitations()
{
return $this->hasMany( 'App\Invitation', 'invitee_id', 'id' );
}
Invitation.php (Model)
This model has another method that would return the inviter detail of an invitation.
public function inviter()
{
return $this->hasOne( 'App\User', 'id', 'invited_by' );
}
If i want to retrieve all invitations of current user it works,
\Auth::user()->invitations;
But if i try to get the information about the inviter it won't work! (Question: How to do it?)
\Auth::user()->invitations->inviter;
Though i can query the inviter from a invitation eloquent object like this,
\App\Invitation::first()->inviter;
But this is not working when i try to access it from the user model -> invitation -> inviter!
Also can i use eager loading here?
\Auth::user()->invitations->inviter;
Looking at this, it appears that you're attempting to retrieve the inviter property from a collection of invitations. The reason Ken's suggestion to use \App\Invitation::first()->inviter; worked is because you are retrieving the inviter of only one invitation (in this instance, the first). To resolve this, loop through your invites before attempting to retrieve the properties for each one:
$invitations = \Auth::user()->invitations;
foreach ($invitations as $invitation) {
$inviter = $invitation->inviter;
}
There is also an each() method specific to Laravel Collections that will allow you to loop through your object.

sync method undefined laravel

I have a relationship in my laravel application,
//Organsiation __has_many__ users (members)
public function users()
{
return $this->belongsToMany('User')->withPivot('is_admin');
}
public function organisations()
{
return $this->belongsToMany('Organisation')->withPivot('is_admin');
}
When I edit an organisation I try and sync the organisation_user table using,
$organisation->users()->sync($members);
The argument passed looks like this,
array(1 => array('is_admin' => 1)) as it states in the laravel documentation.
However I getting the following error returned from the server,
BadMethodCallException","message":"Call to undefined method Illuminate\\Database\\Query\\Builder::sync()
I am wanting to use sync as if my $members array contains new members, or doesnt contain an existing member, it will update the pivot table correctly, what I cannot understand is why it is not working.
I thought sync() was meant for many-to-many relationships?

Categories