i'm gonna to access my 3rd table form 1st . my tables design already in below :
1st Table : User
- id (PK)
- name
- 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 ??