DEV Community

DCodeMania
DCodeMania

Posted on • Originally published at dcodemania.com

Multi-Role System in Laravel

In Laravel, you can implement a multi-role system by utilizing various built-in features and techniques. Here's a general approach to implementing a multi-role system using Laravel:

  • Database Setup: Start by setting up your database tables. You'll need at least three tables: users, roles, and role_user(a pivot table to establish a many-to-many relationship between users and roles).
users
- id
- name
- email
- password

roles
- id
- name

role_user
- role_id
- user_id
Enter fullscreen mode Exit fullscreen mode
  • Define Models and Relationships: Create the corresponding models for your tables and define the relationships between them.
// User.php
public function roles()
{
    return $this->belongsToMany(Role::class, 'role_user');
}

public function hasRole($role)
{
    return $this->roles->contains('name', $role);
}

// Role.php
public function users()
{
    return $this->belongsToMany(User::class, 'role_user');
}
Enter fullscreen mode Exit fullscreen mode
  • Middleware: Create a middleware to check if a user has the required role to access specific routes or perform certain actions.
// RoleMiddleware.php
public function handle($request, Closure $next, $role)
{
    if (!auth()->user()->hasRole($role)) {
        abort(403, 'Unauthorized');
    }

    return $next($request);
}
Enter fullscreen mode Exit fullscreen mode
  • Route Protection: Apply the middleware to the routes that require specific roles.
// web.php
Route::group(['middleware' => ['auth', 'role:admin']], function () {
    // Routes accessible only to users with 'admin' role
});

Route::group(['middleware' => ['auth', 'role:editor']], function () {
    // Routes accessible only to users with 'editor' role
});
Enter fullscreen mode Exit fullscreen mode
  • User Registration and Role Assignment: When registering a user, assign a default role to them.
// RegisterController.php
protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    $user->roles()->attach(Role::where('name', 'default')->first());

    return $user;
}
Enter fullscreen mode Exit fullscreen mode
  • Checking Roles in Views: You can also check a user's role in your views to conditionally show or hide content.
// dashboard.blade.php
@role('admin')
    <!-- Show admin-specific content -->
@endrole

@role('editor')
    <!-- Show editor-specific content -->
@endrole
Enter fullscreen mode Exit fullscreen mode

This is a basic outline of implementing a multi-role system in Laravel. You can further customize and extend it based on your specific requirements. Additionally, consider exploring Laravel's authorization policies and gates for more fine-grained control over user permissions.

Top comments (0)