A
A
Alexander Ampleev2019-02-09 18:43:48
Laravel
Alexander Ampleev, 2019-02-09 18:43:48

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);
    }

Returns null
The role_user table is filled with data.
Route:
Route::get('user/{user_id}/roles', '[email protected]_roles_by_user');

Role Model
<?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);
    }
}

Model 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);
    }
}

table with data:
5c5ef4fdc7fc1739611757.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question