Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsToMany relationship with only one result

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.

like image 548
Gonçalo Marrafa Avatar asked Dec 22 '22 23:12

Gonçalo Marrafa


1 Answers

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
{
    
}
like image 184
Maciej Toborek Avatar answered Jan 13 '23 18:01

Maciej Toborek