Queries of records in tables many to many with laravel

0

How would you do when checking the records of two related tables (many to many) using a pivot table of laravel?

I try to do it with Joins, but I can not find what I want. The tables are:

user
role_user
roles
    
asked by Erain Moya 14.12.2016 в 16:39
source

1 answer

1

Assuming that the relationships are well defined in the models, you just have to do:

$user->role;

The documentation explains this in detail: link

Ideally, your tables should be called users (with s at the end), roles and role_user , which should contain user_id and role_id .

From then on, configuring the models is very simple:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Role:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

Edit:

A quick example to show users with their roles:

Controller

public function index()
{
    $users = User::all();

    return view('users.list', compact('users'));
}

View

@foreach($users as $user)
    Usuario: {{ $user->name }} Rol: {{ $user->role->role_name }}
@endofeach

Obviously the names of the properties change. I recommend you read how relations work in Laravel: link

    
answered by 14.12.2016 / 16:51
source