Answer the question
In order to leave comments, you need to log in
many to many laravel 5.3?
I try the simplest example and code
public function get_roles_by_user($user_id)
{
$user = Role::find($user_id);
dump($user->roles);
}
Route::get('user/{user_id}/roles', '[email protected]_roles_by_user');
<?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);
}
}
<?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);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question