Laravel 8 User Roles And Permissions Tutorial With Laratrust

Hello Artisan,

Today I am coming with a brand new tutorial for you on the topic of laratrust for laravel 8. In this laravel roles and permissions example, I will use laravel laratrus package to control user access. So in this role and permission in laravel 8 tutorial, i will use laratrust pacakge.

I have already created a tutorial on it that was Laravel roles and permissions example without packages. We can control user access and permissions using many packages in Laravel. There are many packages. Spatie and Laratrust are more popular than others.

In this example, I will share with you that how we can manage user roles and permission in laravel using only one custom middleware with Laratrust package. You know that Laratrust is a Laravel package that lets you handle very easily roles and permissions inside your application.

You can read my previous tutorial on laravel roles and permissions example which was without packages. Finished this below tutorial before starting with Laratrust. If you complete my roles and permissions tutorial without package article, then you will easily understand that how laratrust package work and handle user access control in Laravel application.

I will share the source code with you step by step so that you can understand it easily. Check the laratrust package documentation before starting this tutorial:

 

Recommended : User Roles and Permissions Tutorial in Laravel Without Packages

 

Let's start our laravel user roles and permissions from scratch:

 

Step 1 : Download Laravel

To create laratrust for laravel 8, open up your terminal and create a new Laravel project by typing in the following command

composer create-project --prefer-dist laravel/laravel blog

 

Step 2:  Create Auth

We are going to create laravel user roles and permissions with laratrust package so If you are using laravel version 6 then run below command to make auth

composer require laravel/ui --dev
php artisan ui vue --auth
npm install
npm run watch

 

If you are using below laravel version 6 then run below command to make auth

php artisan make:auth

 

Step 3: Setup Laratrust

You can install the package using composer:

composer require santigarcor/laratrust

 

Publish the configuration file:

php artisan vendor:publish --tag="laratrust"

 

Warning: If this command did not publish any files, chances are, the Laratrust service provider hasn't been registered. Try clearing your configuration cache

Run this command to clear application config cache:

php artisan config:clear

 

Run the setup command, keep remember that Before running the command go to your config/laratrust.php file and change the values according to your needs.

php artisan laratrust:setup

 

Dump the autoloader:

composer dump-autoload

 

And now finally run the migrations:

php artisan migrate

 

Step 4: Create Seeder

To check user roles and permissions in Laravel, we need some fake dummy data. We will create it using database seeder. So run below command:

php artisan make:seeder RoleSeeder
php artisan make:seeder PermissionSeeder

 

Now update those both file like below:

Database\Seeders\RoleSeeder.php

namespace Database\Seeders;

use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Seeder;

class RoleSeeder extends Seeder
{

    public function run()
    {
        $roles = [
            [
                'name' => 'Admin',
                'display_name' => 'Admin',
                'description' => 'Can access all features!'
            ],
            [
                'name' => 'Buyer',
                'display_name' => 'Buyer',
                'description' => 'Can access limited features!'
            ],
        ];

        foreach ($roles as $key => $value) {
            $role = Role::create([
                'name' => $value['name'],
                'display_name' => $value['display_name'],
                'description' => $value['description']
            ]);

            User::first()->attachRole($role);
        }
    }
}

 

Now update permission seeder like below:

Database\Seeders\PermissionSeeder.php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Permission;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Route;

class PermissionSeeder extends Seeder
{
    public function run()
    {

        $permissons = [
            [
                'name' => 'CheckController@index',
                'display_name' => 'Index',
                'description' => 'Check'
            ],
            [
                'name' => 'CheckController@create',
                'display_name' => 'Create',
                'description' => 'Check'
            ],
        ];

        foreach ($permissons as $key => $value) {

            $permission = Permission::create([
                            'name' => $value['name'],
                            'display_name' => $value['display_name'],
                            'description' => $value['description']
                        ]);

            User::first()->attachPermission($permission);
        }
    }
}

 

Now register both seeder in database seeder file like that:

Database\Seeders\DatabaseSeeder.php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Database\Seeders\RoleSeeder;
use Database\Seeders\PermissionSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\User::factory(2)->create();
        $this->call(PermissionSeeder::class);
        $this->call(RoleSeeder::class);
    }
}

 

Now run the db:seed command to generate some fake data.

php artisan db:seed

 

After running this command, you will see the following changes in your table like:

users table

laravel-role-and-permission-example-permission-user-table

 

roles table

user-roles-and-permissions-example-roles-table

 

permissions table

user-roles-and-permissions-example-laravel-permissions-table

 

role_user table

laravel-roles-and-permissions-example-using-packages-role-user-table

 

role_permission table

permissions-roles-table-laravel-example

 

permission_user table

laravel-role-and-permission-example-permission-user-table

 

Step 5: Update User Model

In this step, we have to update User model. So update it like below.

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 Laratrust\Traits\LaratrustUserTrait;

class User extends Authenticatable
{
    use LaratrustUserTrait, HasApiTokens, HasFactory, Notifiable;
}

 

Step 6: Create Middleware

Now we need to create our custom middleware. Using this middleware we have to check user permissions.We will just use this middleware in our route. Our middleware automatically controls user roles and permission in laravel.

 

Run this below command to create middleware.

php artisan make:middleware HasPermission

 

Now update this middleware like below:

App\Http\Middleware\HasPermission.php

namespace App\Http\Middleware;

use Closure;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class HasPermission
{

    public function handle($request, Closure $next)
    {

        $_exist_role_user = \DB::table('role_user')
                        ->where('user_id',auth()->id())
                        ->exists();
        
        if( $_exist_role_user ) {

            $user_role = \DB::table('role_user')
                            ->where('user_id',auth()->id())
                            ->first();

            $controllerAction = class_basename(Route::currentRouteAction());
    
            $permission = false;
            $permission_id_id = 0;

            $permission_result = Permission::where('name',$controllerAction)
                                    ->exists();
            
            $permission_id = Permission::where('name',$controllerAction)
                                ->first();
    
            if(!$permission_result) {
                $permission_id_id = 0;
            }
            else {
                $permission_id_id = $permission_id->id;
            }
            
            $role_id = $user_role->role_id;
    
            $check_permission = \DB::table('permission_role')
                                ->where('role_id',$role_id)
                                ->where('permission_id',$permission_id_id)
                                ->exists();
    
            if($check_permission) {
    
                $permission = true;
    
                if($permission) {
                    return $next($request);
                }
    
                return abort(403);

            }else {
                return abort(403);
            }
        }else {
            return 'you are not authorize!';
        }
    }
}

 

Now register middleware in your kernel.php file in $routeMiddleware array  like below.

App\Http\Kernel.php

protected $routeMiddleware = [
  'HasPermission' => \App\Http\Middleware\HasPermission::class,
];

 

Step 7: Create Route

We need to check some route to check user permission is actually working or not. So let's update.

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CheckController;
use App\Http\Controllers\HomeController;

Auth::routes();

Route::middleware(['auth','HasPermission'])->group(function () {
    Route::get('/create',[CheckController::class, 'create']);
    Route::get('/',[CheckController::class, 'index']);
    Route::get('/home', [HomeController::class, 'index'])->name('home');
});

 

Step 8: Create Controller

We are in the final step before testing our roles and permission in laravel using laratrust packages. So let's create it.

App\Http\Controllers\CheckController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;

class CheckController extends Controller
{
    public function index()
    {
      return 'Silence is golden!';
    }
  
    public function create()
    {
      return view('welcome');
    }
}

 

Now all are set to go. Now you can check your application users' roles and permissions by visiting this URL after running the server.

php artisan serve

 

And visit the following url:

 

url
http://127.0.0.1:8000

 

Now you can test after login in your system. Hope it can help you.

 

#laravel #laravel-8x #acl #permission #role #authorization