A project I’ve taken over creates relationships in a rather odd way that I’ve never seen done before.
consider one such example:
public function invites(): BelongsToMany
{
return $this->belongsToMany(
Invite::class,
'user_invites',
'id',
'user_id'
)->where('is_active', 1);
}
I have concerns for such code as Laravel doesn’t seem to endorse such use and also phpstan raises concerns about it as well.
My question is, should I consider refactoring the code so the relationship isn’t being setup this way or is this fine and I just need to tell phpstan to ignore this.
2
Answers
Putting a where clause in the relationship function, while uncommon, doesn’t seem to be discouraged in Laravel’s documentation:
https://laravel.com/docs/11.x/eloquent-relationships#advanced-has-one-of-many-relationships
https://laravel.com/docs/11.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns
This is fine
but this is better: