2
votes

i'm gonna to access my 3rd table form 1st . my tables design already in below :

1st Table : User

  • id (PK)
  • name
  • email
  • password

2nd Table : User_Role

  • id (PK)
  • user_id (foreign)
  • role_id (foreign)

3rd Table : Roles

  • id (PK)
  • authority
  • title

My User Model class code is :

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function user_role()
    {
        return $this->belongsToMany(UserRole::class)->withTimestamps();
    }


}

And My User_Role model class is :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserRole extends Model
{

    public function roles()
    {
        return $this->belongsToMany(Role::class)->withTimestamps();
    }
}

now how can i access to my 2nd tbl filed for example :

$user =  User::find(Auth::id());
return $user->user_role->first()->id;

and how can i access to my 3rd tbl filed ??

title from Roles Table ??

is my table's relations correct ??

1
You should define your Roles model, instead of the User_Role model. Please let me write an answer belowhktang
Make a model for the Third table , Role, not Roleshktang

1 Answers

2
votes

In your User model, you should define its relationship with Role, not with user_role.

In your User model:

public function roles()
{
    return $this->belongsToMany(Role::class, 'user_role');
}

Then in Role model:

public function users()
{
    return $this->belongsToMany(User::class, 'user_role');
}

Laravel will assume the pivot table for n:m relationship to be "user_role". So you don't need to specify the table name, although you can (as shown above).

To get first user Role, you just do:

$user = Auth::user();
$user->roles->first();