I have a relationship between two tables with a join table that only has one result.
When I define a Laravel belongsToMany relationship, instead of returning a collection with only one element I would like to have it return that item alone.
Is there a way to model this in Laravel?
Thanks in advance.
[EDIT]
I'll try to explain what I want using the classic Users/Roles example. Besides de users
and roles
tables, we'll have a users_roles
pivot table which will store all the roles the user has had. A user can, at any given time, have only one active role (identified by the active
attribute being true
).
class User {
function role() {
return $this->belongsToMany('App\Role')->wherePivot('active', 'true');
}
}
With this relationship definition, when I access $user->role
I get a collection (with only one element) of Roles. What I would like is to have that Role instance directly.
In my case that was the most straight forward solution:
class User extends Model {
public function services()
{
return $this->belongsToMany(Service::class, 'service_user')
->using(ServiceUser::class)
->withPivot('user_id', 'service_id', 'is_main_service');
}
public function mainService()
{
return $this->hasOneThrough(Service::class, ServiceUser::class, 'user_id', 'id', 'id', 'service_id')
->where('is_main_service', 1);
}
}
Pivot table class:
use Illuminate\Database\Eloquent\Relations\Pivot;
class ServiceUser extends Pivot
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With