Debug School

rakesh kumar
rakesh kumar

Posted on

How to implement a role-based redirection and dashboard in laravel

Create the Livewire Component
First, you'll need a Livewire component for handling the login functionality. If you haven't already created the component, you can generate it using the following Artisan command:

php artisan make:livewire Login
Enter fullscreen mode Exit fullscreen mode
  1. The Livewire View (login.blade.php) Here's a simple form for the login functionality in Livewire:
<div>
    <form wire:submit.prevent="login">
        <input type="email" wire:model="email" placeholder="Email">
        <input type="password" wire:model="password" placeholder="Password">
        <button type="submit">Login</button>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode
  1. The Livewire Component (Login.php) In the Livewire component, you will handle the login logic and redirection based on the role ID:
namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class Login extends Component
{
    public $email;
    public $password;

    public function render()
    {
        return view('livewire.login');
    }

    public function login()
    {
        $credentials = ['email' => $this->email, 'password' => $this->password];

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            switch ($user->role_id) {
                case 1:
                    return redirect()->to('/dashboard-admin');
                case 2:
                    return redirect()->to('/dashboard-manager');
                case 3:
                    return redirect()->to('/dashboard-user');
                default:
                    return redirect()->to('/');
            }
        } else {
            session()->flash('error', 'Invalid credentials');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Notes:
Ensure that the $email and $password properties are properly bound to your form inputs using wire:model.
The login() method performs the authentication check. If successful, it redirects the user based on their role ID.
Update the role ID cases (case 1, case 2, case 3) to match your application's specific roles and the corresponding URLs for each dashboard.
Make sure that your routes (/dashboard-admin, /dashboard-manager, /dashboard-user) are defined in your Laravel routes file.
Adding Route Definitions
Ensure you have the routes set up in your web.php:

Route::get('/dashboard-admin', [AdminController::class, 'index'])->name('dashboard.admin');
Route::get('/dashboard-manager', [ManagerController::class, 'index'])->name('dashboard.manager');
Route::get('/dashboard-user', [UserController::class, 'index'])->name('dashboard.user');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)