Code Lover
Code Lover

Reputation: 8348

Laravel - Cannot get Roles for Admin guard

I have a frontend and admin areas. The frontend using the Auth package from Laravel and for the Admin I am using an admin guard and all views, controller, and models are under admin directory.

I am trying to set up the roles and permissions for both frontend and admin users using the same Role and Permission model. For that, I have created following tables

Tables

The problem: I am able to get roles for the frontend users using belongsToMany() but not for the admin. Here is the code.

User Model

namespace App;

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

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',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function admin_roles()
    {
        return $this->belongsToMany('App\Admin\Role', 'role_admin');
    }

    public function roles() {
        return $this->belongsToMany('App\Admin\Role');
    }
}

Role Model

namespace App\Admin;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name', 'display'];

    public function permissions()
    {
        return $this->belongsToMany('App\Admin\Permission');
    }

    public function admin_users()
    {
        return $this->belongsToMany('App\User');
    }

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

}

Frontend View

{{auth()->user()->roles}}

// output 
[{"id":1,"name":"admin","display":"Admin","created_at":null,"updated_at":null,"pivot":{"user_id":1,"role_id":1}},{"id":2,"name":"supervisor","display":"Supervisor","created_at":null,"updated_at":null,"pivot":{"user_id":1,"role_id":2}}]

Admin View

{{auth()->user()->admin_roles}}
//output
null - checked with dd()

Edit

Table Structure

role_admin

Schema::create('role_admin', function (Blueprint $table) {
    $table->bigInteger('role_id')->unsigned();
    $table->bigInteger('admin_id')->unsigned();
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade');
});

role_user

Schema::create('role_user', function (Blueprint $table) {
    $table->bigInteger('role_id')->unsigned();
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

roles

Schema::create('roles', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->text('display');
    $table->timestamps();
});

permissions

Schema::create('permissions', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('model');
    $table->string('can');
    $table->timestamps();
});

permission_role

Schema::create('permission_role', function (Blueprint $table) {
    $table->bigInteger('permission_id')->unsigned();
    $table->bigInteger('role_id')->unsigned();

    $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});

admin

Schema::create('admins', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Admin Model

 <?php

namespace App\Admin;

use App\Notifications\Admin\ResetPasswordNotification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';

    /**
     * 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',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }
}

Working Code Is Here

I have set the relationship for the role_admin it to the Admin model which was wrongly placed in the User model before.

<?php

namespace App\Admin;

use App\Notifications\Admin\ResetPasswordNotification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';

    /**
     * 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',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    public function roles()
    {
        return $this->belongsToMany('App\Admin\Role', 'role_admin');
    }
}

Upvotes: 0

Views: 1046

Answers (2)

Yomna Hesham
Yomna Hesham

Reputation: 472

The problem is that you use the model User instead of Admin

To recover this:

  1. Remove the admin_roles relation from the User model and place it in the Admin model.
  2. Modify the admin_users relation in the Roles model to be connected with the Admin model instead of the User model, so it should be like that return $this->belongsToMany('App\Admin\Admin');

Upvotes: 1

Qonvex620
Qonvex620

Reputation: 3972

Seems your admin_roles relationship is in your User model, but in your migration you had declared the foreign key to admins table. like this one

$table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade');

Now, let's assume that you logged as an admin , then your Admin model also should has this relationship.

public function admin_roles()
{
    return $this->belongsToMany('App\Admin\Role', 'role_admin', 'admin_id', 'role_id');
}

Upvotes: 1

Related Questions