Make User-Roles by using eloquent method with pivot-table in Laravel 9

Make User-Roles by using eloquent method with pivot-table in Laravel 9

11-Sep-2022
| |
Image Carousel

In many cases using laravel how could you define user's role like if my user has role customer then u may define is_role or role  by column name in users table.


This works when your user has only single role but what if user has many roles like a user is a admin as well as customer , the option we have is to create a new user , but we have another option to attach many roles to a single user. we will make a function to attach different roles and call a function to get all users for role customer , in this example we will use Customer role

  Following steps :

  • Creating Model and Migration name Role.
  • Run migration
  • Creating Customer role
  • Creating User and attach Customer role
  • Get all Customer

We will create a Model name Role and a migration file for creating table in database , in CMD or TERMINAL hit the folloeing commandCopy

 php artisan make:model Role -m

This wiil create app/Models/Role.php and database/migrations/your timespan_create_roles_table.php files.
Inside database/migrations/your timespan_create_roles_table.php replace the following codeCopy


 

<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
};

 

 

After that now will create pivot table named user_roles  where we use user_id and role_id as foreign key as following.Copy

php artisan make:migration create_user_roles_table

Inside database/migrations/your timespan_create_user_roles_table.php replace the following code , as shown we are using foreign keys user_id and role_id from refrence users and roles as pivot table.Copy

<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
 
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_roles');
    }
};

 

Now run the followig command in your CMD and TERMINAL for creating roles and user_roles table Copy

php artisan migrate 

 

 

In user_roles Pivot table

Inside app/Models/User.php paste the following code Copy

<?php
 
namespace App\Models;
 
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
use URL;
 
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
 
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
 
    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
 
 
 
    public function roles()
    {
        return $this->belongsToMany(Role::class,'user_roles');
    }
   
    public function hasRole(... $roles )
    {
        foreach ($roles as $role) {
            if ($this->roles->contains('slug', $role)) {
                return true;
            }
        }
        return false;
    }
}

 

Now we had creted Role model along with migration , so now we will create Customer role and after will create user Custtomer and attach the role.
In web.php file Copy

use App\Models\Role;

Route::get('/createRole', function () {
   $role         =  new Role();
   $role->name   =  'Customer';
  $role->slug   =  'customer';
  $role->save();
});

This wiil create a new role name Customer in database table roles.
After that now will create a customer so use any url along with controller to create a customer. Copy

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use Hash;
 
use Auth;
class DeveloperCorner extends Controller
{
 
  public function createCustomer()
    {
      $user         =  new User();
      $user->name   =  'Developer';
      $user->email   =  '[email protected]';
      $user->password = Hash::make('1234');
      $user->save();
 
      $customer = Role::where('slug','customer')->first();
 
      $user->roles()->attach($customer);
    }
 
   
}

 

now your user_roles look something like this , as this is the pivot table where we use user_id and role_id as foreign keys from users and roles.

Now we will get al  the list of users having role Customer .Copy

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use Hash;
 
use Auth;
class DeveloperCorner extends Controller
{
  public function createCustomer()
    {
      $user         =  new User();
      $user->name   =  'Developer';
      $user->email   =  '[email protected]';
      $user->password = Hash::make('1234');
      $user->save();
 
      $customer = Role::where('slug','customer')->first();
 
      $user->roles()->attach($customer);
    }
 
    public function getCustomer()
    {
      $role = 'customer';
      $customer     = User::whereHas('roles', function ($q) use ($role) {
          $q->where('slug', $role);
      })->get();
 
      echo"<pre>";print_r($customer);
    }
 
 
}

 

And to use the condition to check the role of the user in middleware or in any other file use this Copy

  public function checkCustomer()
    {
      if(Auth::User()->hasRole('customer')){
 
      }
    }

 

Tags: how to make user-roles using laravel 9 , how to define roles in laravel , make user's roles , user has many roles in laravel 9 , define user has many roles in laravel 9,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
Related Articles
Load More

Newsletter