Implementing User Roles and Permissions in Laravel

Introduction laravel user rules
Implementing laravel user roles and permissions is a crucial aspect of building robust and secure Laravel applications. In this guide, we'll explore how to add user rules to your Laravel project using a global helper function and database migration.

Creating a Global Helper Function
To efficiently manage user rules across your application, let's create a global helper function:

1. Create a Helper File:

Create a new file named LaravelProject/app/http/helpers.php within your app directory.

2. Define the Function:

Inside helpers.php, add the following code:

if (! function_exists('getUserRules')) {
  function getUserRules() {
    $currentUserId = auth()->check() ? auth()->id() : 0;
    $rules = DB::table('tblrules')
      ->where('userid', $currentUserId)
      ->get();
    return $rules;
  }
}


3. Register the Helper Function:

Update your composer.json file:
Open your composer.json file and add the following to the autoload section:

"autoload": {
  "files": [
    "app/helpers.php"
  ]
},


Dump Autoload:
Run the following command in your terminal:
composer dump-autoload


Creating the tblrules Table
To store user rules, we'll create a database table:

1. Generate Migration:

Run in your terminal.
php artisan make:migration create_tblrules_table 


2. Define Table Structure:
Update the migration file with the following:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
  public function up(): void
  {
    Schema::create('tblrules', function (Blueprint $table) {
      $table->id();
      $table->integer('userid'); 
      $table->string('rules')->default('NA');
      $table->timestamps();
    });
  }

  public function down(): void
  {
    Schema::dropIfExists('tblrules');
  }
};


In your laravel controller

public function index(Request $request) {
 $rules = getUserRules(); //this is called from helper.php
 $hasAdmin = $rules->contains('rules', 'admin');
 $hasSupervisor = $rules->contains('rules', 'supervisor');
 $hasEmployee = $rules->contains('rules', 'employee');
 return view('your_view_name', compact('hasAdmin', 'hasSupervisor', 'hasEmployee'));
}


your_view_name.blade.php

@if ($hasAdmin)
  <h1>Has Admin Rules</h1>
@endif
@if ($hasSupervisor)
  <h1>Has Supervisor Rules</h1>
@endif
@if ($hasEmployee)
  <h1>Has Employee Rules</h1>
@endif


Additional Considerations
Security: Implement proper authentication and authorization mechanisms to protect user data.
Performance: Consider optimizing database queries for large datasets.
Flexibility: Explore using a more flexible rule system for complex permission structures.
Testing: Write unit tests to ensure the helper function and rule checks work as expected.
By following these steps, you've established a foundation for managing user rules in your Laravel application. Remember to adapt the code to your specific project requirements and security standards.

Thanks for reading this post.

Additional Search keyword: laravel rules, laravel roles

Last update on Jul 14, 2024

Tags: laravel

Back to Posts

Comments

No comments yet.

ForceTeach Corporation 2024