How to make custom login only for admin in laravel?

by giovanny.lueilwitz , in category: PHP Frameworks , 10 months ago

How to make custom login only for admin in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 7 months ago

@giovanny.lueilwitz 

To create a custom login for only admin in Laravel, you can follow these steps:


Step 1: Create a new middleware called AdminMiddleware by running the following command in your terminal:

1
php artisan make:middleware AdminMiddleware


Step 2: Update the handle method of the AdminMiddleware to check if the user logging in is an admin. You can do this by adding the following code to the handle method:

1
2
3
4
5
6
7
8
public function handle($request, Closure $next)
{
    if ($request->user() && $request->user()->role !== 'admin') {
        return redirect('home');
    }

    return $next($request);
}


Step 3: Register the AdminMiddleware in the $routeMiddleware property of your app/Http/Kernel.php file:

1
2
3
4
protected $routeMiddleware = [
    // other middlewares
    'admin' => AppHttpMiddlewareAdminMiddleware::class,
];


Step 4: Apply the AdminMiddleware to the routes that need to be restricted to admin access by using the middleware method in your routes/web.php file or in your routes defined in the RouteServiceProvider:

1
2
3
Route::middleware(['admin'])->group(function () {
    // admin only routes here
});


Step 5: Update your login method in the AuthLoginController to check if the user is an admin before authenticating:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use IlluminateSupportFacadesAuth;

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials) && Auth::user()->role === 'admin') {
        return redirect()->intended('dashboard');
    }
    
    return redirect('login')->with('error', 'These credentials do not match our records.');
}


By following these steps, you can create a custom login functionality for admin users in Laravel.

Related Threads:

How to login in Drupal admin panel?
How to login to admin panel in joomla?
How to login to admin panel in Magento?
How to make custom authentication on laravel?
How to separate user session from admin session in laravel?
How to make auto login in shopify site?