How to Make Custom Login Only For Admin In Laravel?

14 minutes read

In order to create a custom login system for admins in Laravel, you can follow these steps:

  1. Create a new column in your users table to store the admin status of each user.
  2. Define a custom guard for admin users in your config/auth.php file.
  3. Create a new admin authentication controller using the artisan command php artisan make:controller AdminAuthController.
  4. Customize the login and logout methods in the AdminAuthController to only allow admin users to login.
  5. Define routes for the admin authentication using the Route::group method in your routes/web.php file.
  6. Update your login form to direct admin users to the admin login route.
  7. Create middleware to check if a user is an admin before allowing access to admin-specific routes.


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

Best Laravel Books of July 2024 (Copy)

1
Laravel: Up and Running: A Framework for Building Modern PHP Apps

Rating is 5 out of 5

Laravel: Up and Running: A Framework for Building Modern PHP Apps

2
Laravel: Up & Running: A Framework for Building Modern PHP Apps

Rating is 4.9 out of 5

Laravel: Up & Running: A Framework for Building Modern PHP Apps

3
Practical Laravel: Develop clean MVC web applications

Rating is 4.8 out of 5

Practical Laravel: Develop clean MVC web applications

4
PHP & MySQL: Server-side Web Development

Rating is 4.7 out of 5

PHP & MySQL: Server-side Web Development

5
Laravel Unleashed: Mastering Modern PHP Development (The Laravel Mastery Series: Unleashing the Power of Modern PHP Development)

Rating is 4.6 out of 5

Laravel Unleashed: Mastering Modern PHP Development (The Laravel Mastery Series: Unleashing the Power of Modern PHP Development)

6
Beginning Laravel: Build Websites with Laravel 5.8

Rating is 4.5 out of 5

Beginning Laravel: Build Websites with Laravel 5.8

7
PHP 8 Objects, Patterns, and Practice: Mastering OO Enhancements, Design Patterns, and Essential Development Tools

Rating is 4.4 out of 5

PHP 8 Objects, Patterns, and Practice: Mastering OO Enhancements, Design Patterns, and Essential Development Tools

8
Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

Rating is 4.3 out of 5

Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

9
Murach's PHP and MySQL (4th Edition)

Rating is 4.2 out of 5

Murach's PHP and MySQL (4th Edition)


How to customize the login process for admin users in Laravel?

To customize the login process for admin users in Laravel, you can follow these steps:

  1. Create a new LoginController for admin users by running the following command in your terminal:
1
php artisan make:controller AdminLoginController


  1. Implement the necessary logic for authenticating admin users in the AdminLoginController. You can customize the login process by checking if the user's role is 'admin' and if the credentials are correct.
  2. Next, update the routes/web.php file to add a route for the admin login page. You can use the following code as a reference:
1
2
Route::get('admin/login', 'AdminLoginController@showLoginForm')->name('admin.login');
Route::post('admin/login', 'AdminLoginController@login')->name('admin.login.submit');


  1. Create a new view file for the admin login form in the resources/views/auth directory. You can customize the form fields and layout according to your requirements.
  2. Update the authenticate method in the app/Http/Controllers/Auth/LoginController.php file to redirect admin users to the admin dashboard after successful login. You can use the following code snippet as a reference:
1
2
3
4
5
6
7
8
protected function redirectTo()
{
    if (Auth::user()->role === 'admin') {
        return '/admin/dashboard';
    } else {
        return '/home';
    }
}


  1. Lastly, make sure to update the auth middleware in your routes to handle the authentication for admin users. You can use the following code snippet as a reference:
1
2
3
Route::group(['middleware' => 'auth'], function () {
    Route::get('/admin/dashboard', 'AdminDashboardController@index')->name('admin.dashboard');
});


By following these steps, you can customize the login process for admin users in Laravel and create a separate login flow for them.


How to create a custom auth provider for admin users in Laravel?

To create a custom auth provider for admin users in Laravel, you can follow these steps:


Step 1: Create a new auth guard for admin users in the config/auth.php file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],


Step 2: Create a new model for admin users (e.g. Admin.php) in the app/Models directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $guard = 'admin';

    // Other properties and methods
}


Step 3: Create a custom auth provider for admin users by extending the AuthServiceProvider in the app/Providers directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        // Your policies here
    ];

    public function boot()
    {
        $this->registerPolicies();

        Gate::define('admin', function ($user) {
            return $user->isAdmin();
        });
    }
}


Step 4: Use the new guard for admin users in your routes and controllers by specifying the guard name in the auth middleware:

1
2
3
Route::group(['middleware' => 'auth:admin'], function() {
    // Your admin routes here
});


With these steps, you can create a custom auth provider for admin users in Laravel. Just make sure to adjust the code according to your specific requirements and user authentication logic.


How to set up a custom login page for admin users in Laravel?

To set up a custom login page for admin users in Laravel, follow these steps:

  1. Create a new route for the custom admin login page in your routes/web.php file:
1
2
Route::get('admin/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('admin/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');


  1. Create a new controller for handling the admin login:
1
php artisan make:controller Auth/AdminLoginController


  1. In the newly created AdminLoginController, add the showLoginForm and login methods:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use Illuminate\Http\Request;

public function showLoginForm()
{
    return view('auth.admin-login');
}

public function login(Request $request)
{
    // Validate the form data
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required|min:6',
    ]);

    // Attempt to log the user in
    if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
        // If successful, then redirect to their intended location
        return redirect()->intended(route('admin.dashboard'));
    }

    // If unsuccessful, then redirect back to the login with the form data
    return redirect()->back()->withInput($request->only('email', 'remember'));
}


  1. Create a new view file (e.g. resources/views/auth/admin-login.blade.php) for the admin login form:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@extends('layouts.app')

@section('content')
    <form method="POST" action="{{ route('admin.login.submit') }}">
        @csrf

        <label for="email">Email</label>
        <input type="email" id="email" name="email" value="{{ old('email') }}" required autofocus>

        <label for="password">Password</label>
        <input type="password" id="password" name="password" required>

        <input type="checkbox" id="remember" name="remember">
        <label for="remember">Remember Me</label>

        <button type="submit">Login</button>
    </form>
@endsection


  1. Update your config/auth.php file to use the admin guard:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
],


  1. Update the login route in your LoginController to redirect to the admin login route:
1
protected $redirectTo = '/admin/dashboard';


With these steps, you should now have a custom login page for admin users in Laravel. Make sure to create the necessary Admin model and update the authentication middleware in your routes to use the admin guard for protecting admin routes.


How to create a custom guard for admin users in Laravel?

To create a custom guard for admin users in Laravel, follow these steps:

  1. Define a new guard in the config/auth.php file: Open the config/auth.php file in your Laravel project. Add a new guard configuration under the 'guards' array. For example:
1
2
3
4
5
6
'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],


  1. Define a new user provider for admin users in the same file: Add a new provider configuration under the 'providers' array. For example:
1
2
3
4
5
6
'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],


  1. Define a new middleware for the admin guard: Create a new middleware class for the AdminGuard. For example:
1
php artisan make:middleware AdminGuard


  • Update the handle method in the new AdminGuard middleware to check if the user is an admin. For example:
1
2
3
4
5
6
7
8
public function handle($request, Closure $next)
{
    if (Auth::guard('admin')->check()) {
        return $next($request);
    }

    return redirect('/');
}


  1. Register the new middleware in the app/Http/Kernel.php file: Add the new middleware to the $routeMiddleware array. For example:
1
2
3
protected $routeMiddleware = [
    'auth.admin' => \App\Http\Middleware\AdminGuard::class,
];


  1. Protect your routes using the new middleware: Add the 'auth.admin' middleware to the routes that should be accessible only to admin users. For example:
1
2
3
Route::get('/admin/dashboard', function () {
    // Only accessible to admin users
})->middleware('auth.admin');


  1. Create a model and migration for the admin users: Create a new model for the admin users using the artisan command and define the necessary fields in the migration file. For example:
1
php artisan make:model Admin -m


  1. Update the admin database table schema with the required fields.
  2. Make sure to seed the users table with admin data.


With these steps, you have successfully created a custom guard for admin users in Laravel using a separate guard, provider, middleware, and model. This will allow you to distinguish between regular users and admin users in your application.


How to integrate social login for admin users in Laravel?

To integrate social login for admin users in Laravel, you can follow these steps:

  1. Install a Laravel Socialite package: Use composer to install the Laravel Socialite package by running the following command in your terminal:
1
composer require laravel/socialite


  1. Create OAuth app credentials: Create OAuth app credentials for the social login provider you want to integrate (e.g. Google, Facebook, etc.). Make sure to get the client ID and secret.
  2. Configure services.php: Open the config/services.php file in your Laravel project and add the credentials for the social login provider you want to use. For example, to configure Google login, add the following code:
1
2
3
4
5
'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT_URI'),
],


  1. Create routes: Define routes for social login in your web.php routes file. For example, to create a route for Google login, add the following code:
1
2
Route::get('auth/google', 'Auth\LoginController@redirectToGoogle');
Route::get('auth/google/callback', 'Auth\LoginController@handleGoogleCallback');


  1. Create a controller: Create a controller to handle the social login process. In the controller, create methods to redirect to the social login provider and handle the callback. Here's an example of how the controller methods may look like:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public function redirectToGoogle()
{
    return Socialite::driver('google')->redirect();
}

public function handleGoogleCallback()
{
    $user = Socialite::driver('google')->user();

    // Check if the user is an admin

    // Log in the user
}


  1. Check if the user is an admin: In the handleGoogleCallback method, check if the logged-in user is an admin. You can use the retrieved user data (e.g. email address) to determine if the user is an admin.
  2. Log in the user: If the user is an admin, log them in using Laravel's authentication methods. You can use the Auth facade to manually log in the user.


By following these steps, you should be able to integrate social login for admin users in your Laravel application.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To create a Kotlin login with SQLite, you can follow these steps:Start by setting up the necessary dependencies in your Kotlin project. Include the Kotlin SQLite library in your build.gradle file. Create a layout file for your login screen. It should contain t...
To add custom fields for addresses to WooCommerce products, you can use the functions available in WooCommerce to create custom fields. You would first need to create a custom meta box for the product page where you want to add the custom fields. This can be d...
To create a new page in WordPress, follow these steps:Login to your WordPress admin panel by accessing the &#34;wp-admin&#34; directory of your website.Once logged in, click on &#34;Pages&#34; in the left-hand menu of the admin dashboard.Click on the &#34;Add ...