allUsers error: Call to a member function getKey() on null
Hello everyone,
I've created my own team functionality.
In my TeamResource, i want to add a column in my table which shows the amount of members in a team including the owner.
I have these three functions in my Team model which are identical to both Jetstream and Filament Companies plugin team model:
/**
* Get the owner of the team.
*/
public function owner(): BelongsTo
{
return $this->belongsTo(\App\Models\User::class, 'user_id');
}
/**
* Get all the team's users including its owner.
*/
public function allUsers(): Collection
{
return $this->users->merge([$this->owner]);
}
/**
* Get all the users that belong to the team.
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(\App\Models\User::class, \App\Models\TeamUser::class)
->withTimestamps();
}
And i'm using the following in my resource:
Tables\Columns\TextColumn::make('allUsers_count')
->searchable()
->sortable()
->counts('allUsers'),
The error i'm getting: Call to a member function getKey() on null
I've been trying things out for hours but can't seem to understand why this is happening.
In allUsers() when i try dd($this->users->merge([$this->owner]));
i see an empty array.
But when i do dd($this->users->merge($this->owner()-get()));
I get two results.
However i can't user get() because Filament does the query building in the resource.
Is there anyone who understands what is going wrong here?5 Replies
Hi!
Anyone any idea?
After messing around more, i found that $this->owner returns null
and $this->owner() returns data records.
allUsers must return relationship class not a collection
Funny timing.
I was playing around and the moment you sent this, i got that exact error with what i was trying.
I tried the following:
$a = Team::where('id', 1)->first();
dd($a->allUsers);
With this one i got the error telling me it must return a relation rather than a collection.
doing this: dd($a->allUsers());
Got me a collection of the records.
THen i guess i should count the collections rather than the relations.
Do this way:
Tables\Columns\TextColumn::make('users_count')
->searchable()
->sortable() -> formatStateUsing(fn($state) => $state+1)
->counts('users'),
@Hotcat Yes! That works!
Haha you made my day, thank you!