Пробую простейший пример и код
public function get_roles_by_user($user_id)
{
$user = Role::find($user_id);
dump($user->roles);
}
Возвращает null
Таблица role_user заполнена данными.
Роут:
Route::get('user/{user_id}/roles', 'TestController@get_roles_by_user');
Модель Role
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->belongsToMany(\App\User::class);
}
}
Модель User
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Avatar;
use App\Post;
use App\Role;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* 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 avatar()
{
return $this->hasOne(Avatar::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
public function roles()
{
return $this->belongsToMany(\App\Role::class);
}
}
таблица с данными: