How to create a custom auth guard and make authentication, In this tutorial I will learn about laravel custom login with custom self guard. To create this and setup custom authentication with the guard I will take an example of the students' table instead of the laravel default users table. We already know that laravel gives us a default users table with User Model with authentication.
So in this laravel 9 custom guard authentication tutorial we will see how to create and config a custom guard for the student login system and how we can use it for student authentication. After having finished this tutorial you will complete learning how to make laravel multi auth login with the custom guard in form this tutorial.
Laravel uses the web as the default guard for the session and to make auth uses auth middleware to check whether users are logged in or not. But in this tutorial, we will create our custom guard and make a custom auth login system and how it is used event other multiple guards in the project.
So let's see how to create a custom guard with login student login system making.
Step 1: Create Project
Create laravel 9 projects using the given suggested below command in your terminal. This will take a little time to create a laravel project in your system. This command default will take current version of the laravel.
composer create-project laravel/laravel custom-guard cd custom-guard
Step 2: Config Database
After Successfully creating the laravel project we will config our database. First, I will go to my PHPMyAdmin and create a student name database.
Then we will put this student database name in the .env file you will find in your root file. If not found the .env file in your root just create and copy form .env.example file and config.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=student DB_USERNAME=root DB_PASSWORD=
Laravel-9 Multi Authentication Guard Passport API Example
Step 3: Create Model & Migration & Controller
We will create a model, migration, and controller for the student login system. Using the below-given command it will create a model and migration and controller for the student.
php artisan make:model Student -mc
Now we will add some columns in students migration to add student information etc. Just copy all fields and past them into your student migration.
database/migrations/CreateStudentsTable.php<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('mobile'); $table->string('password'); $table->integer('gr_no'); $table->date('dob'); $table->enum('status',['active','inactive'])->default('active'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } }
After the migration, we will fix our student model.
The first thing we will extend this model to authentication. Then If required you can use HasFactory and Notifiable.
After all imported we will protect guarded attribute as array in the model. then after also we will protect the fillable property and add all the field column names which we added in our migration or student table.
app/Models/Student.php<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class Student extends Authenticatable { use HasFactory, Notifiable; protected $guarded = []; protected $fillable = [ 'name', 'email', 'mobile', 'password', 'gr_no', 'dob', 'status' ]; }
After, all is done student migration and model we will migrate our student table using the given below command.
php artisan migrate
Step 4: Config Student Guard
Now time to register student guard in your auth file. First, we will create a student guard then we will create a provider for the student. just follow below example file in your process.
config/auth.php<?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'student' => [ 'driver' => 'session', 'provider' => 'students', ], // CREATE STUDENT GUARDS ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], 'students' => [ 'driver' => 'eloquent', 'model' => App\Models\Student::class, ], // ADD STUDENT PROVIDER ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that each reset token will be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, 'throttle' => 60, ], 'students' => [ 'provider' => 'students', 'table' => 'password_resets', 'expire' => 60, 'throttle' => 60, ], // ADD PASSWORD RESET ], /* |-------------------------------------------------------------------------- | Password Confirmation Timeout |-------------------------------------------------------------------------- | | Here you may define the amount of seconds before a password confirmation | times out and the user is prompted to re-enter their password via the | confirmation screen. By default, the timeout lasts for three hours. | */ 'password_timeout' => 10800, ];
Step 5: Login Form
In this step, we will create a simple login form where students can enter their credentials and be able to login.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Custom Auth Guard Tutorial - Webappfix</title> </head> <body> @if (Session::has('error')) <font color="red">{{ Session::get('error') }}</font> @endif <form action="{{ route('student.login.submit') }}" method="post" autocomplete="off"> @csrf <label>Email : <input type="email" name="email"> </label> <br> @error('email')<font color="red">{{$message}}</font>@enderror <br> <label>Password : <input type="password" name="password"> </label> <br> @error('password')<font color="red">{{$message}}</font>@enderror <br> <input type="submit" value="login"> </form> </body> </html>
Step 6: StudentController
In this student controller first, we will register a manually student for just demonstration purpose.
In the second method, we will show a student login form.
In the third and last method, we will handel the student login form with validation if validation is successfully passed then it will go to attempt student guard with student email and password. If given credential right and auth attempt will return true else false.
Here without a specific guard name, it will take the default User guard. We must need to specify the guard name here and which guard using you want to authenticate.
App\Http\Controllers\StudentController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use App\Models\Student; class StudentController extends Controller { public function studentRegister() { Student::create([ 'name' => 'Haresh Chauhan', 'email' => 'haresh@gmail.com', 'mobile' => '1234567890', 'password' => bcrypt('123456'), 'dob' => '1999-06-19', 'gr_no' => '85265423' ]); } public function studentLoginForm() { return view('student'); } public function studentLoginSubmit(Request $request) { $this->validate($request,[ 'email' => 'required|email|exists:students', 'password' => 'required' ]); $response = Auth::guard('student')->attempt(['email' => $request->email,'password' => $request->password]); // WILL AUTHENTICATION STUDENT if ($response) { dd(Auth::guard('student')->user()->name.' Login Successfully.'); // CODE AFTER STUDENT AUTHENTICATION }else{ return back()->with('error','Invalid Email Or Password'); } } }
Step 7: Define Route
Here we will define route names these all methods we used in StudentController.
routes/web.php<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\StudentController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('student/register',[StudentController::class,'studentRegister'])->name('student.register'); Route::get('student/login/form',[StudentController::class,'studentLoginForm'])->name('student.login.form'); Route::post('student/login/submit',[StudentController::class,'studentLoginSubmit'])->name('student.login.submit');
Step 8: Start Development Server
Now, We will start our development server using the below-given command.
php artisan server
Register a student for check authentication.
http://127.0.0.1:8000/student/register
Goto student login form.
http://127.0.0.1:8000/student/login/form
Conclusion
Laravel authentication is a powerful user login auth system this framework default auth login system provides but still you want to make your custom and multiple guards you and make your self as you want there is no limit you can create as per your requirement this simple to integrate and very flexible to use for the developer. Apart from that laravel also provides API this API multiple a little bit different from the web this tutorial we will see in the next chapter.
We always thanks to you for reading our blogs.
Dharmesh Chauhan
(Swapinfoway Founder)Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us
Haresh Chauhan
(Co-Founder)We Are Also Recommending You :
- How to create Excel file in Laravel 6
- Trying to access array offset on value of type int
- How to Send Mail using PHPMailer in Laravel?
- Laravel 10 Create Controller Example
- Laravel 6 Cron Job Task Scheduling Tutorial
- Laravel Custom Command Make Example
- How to use Date Format Validation in Laravel?
- Laravel 9 Authorize.Net Payment Gateway Integration
- Laravel 10 Arr::pluck() Helper Function Use Example
- Median() Method | How It is Different From avg() Method In Laravel Collection