Laravel 10 Middleware Tutorial Example
Hello Guys,
In this post, we will learn laravel 10 middleware example. step by step explain laravel 10 custom middleware example. you can see how to create custom middleware in laravel 10. you can see how to use middleware in laravel 10. Let's see below example how to apply middleware in laravel 10.
Laravel Middleware is used to filter HTTP requests in your web application. One of the basic requirements of any web application is an HTTP requests filter, so we have to make one as well for example make auth middleware. auth middleware always checks if you are going then and then you can access those pages.
In this example, we will create one custom middleware that will allow active users to access pages. we will add is_active column in users table and check which user is active or not. so let's follow the below step by step and make it done for example.
Let's follow below steps:
Step 1: Install Laravel
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Create Middleware
In this step, open terminal and run below command to create custom middleware file, so let's run below command:
php artisan make:middleware IsActive
Now, it's created new IsActive.php file. let's update following code on this file.
app/Http/Middleware/IsActive.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class IsActive
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (!auth()->user()->is_active) {
return response()->json('Your account is inactive');
}
return $next($request);
}
}
Step 3: Register Middleware
In this file, we need to register middleware on Kernel.php file. we will call is-active of new created middleware. so let's update following file.
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
....
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
....
'is-active' => \App\Http\Middleware\IsActive::class,
];
}
Step 4: Use Middleware
In this step, we will create one route and show you how to use middleware in route file. so let's open your route file and update following code:
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RSSFeedController;
/*
|--------------------------------------------------------------------------
| 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('/test-user', [App\Http\Controllers\HomeController::class, 'index'])->middleware(['auth', 'is-active']);
Step 5: Create Auth Scaffolding
Here, we will create auth scaffolding so, user can login and check below url. so let's install laravel ui package and generate auth scaffolding.
First you need to install laravel/ui package as like bellow:
composer require laravel/ui
Here, we need to generate auth scaffolding in laravel 10 using laravel ui command. so, let's generate it by bellow command:
php artisan ui bootstrap --auth
Now you need to run npm command, otherwise you can not see better layout of login and register page.
Install NPM:
npm install
Run NPM:
npm run dev
Step 6: Add is_active Column
Here, we will create new migration to add is_active column in users table. so let's create migration and run it.
php artisan make:migration add_is_active_column
Next, simple update below code to migration file.
database/migrations/add_is_active_column.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_active')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
}
};
Next, we need to run migration using below command:
php artisan migrate
Now, we will add is_active column in fallible array of user model. let's update it.
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'is_active'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step 7: Create Seeder
In this step, we will create UserSeeder to generate active and inactive users default. so let's create seeder and create dummy users to check.
php artisan make:seeder UserSeeder
And put bellow code in UserSeeder seeder this way:
database/seeders/UserSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
User::create([
"name" => "One",
"email" => "one@gmail.com",
"password" => Hash::make("123456"),
"is_active" => 1
]);
User::create([
"name" => "Two",
"email" => "two@gmail.com",
"password" => Hash::make("123456"),
"is_active" => 0
]);
}
}
After this we have to run bellow command for run UserSeeder seeder:
php artisan db:seed --class=UserSeeder
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/login
Now you can login with following credentials for InActive User:
Email: two@gmail.com
Password: 123456
After login you have to go to the following URL:
http://localhost:8000/test-user
You will find the following layout:
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 10 ChartJS Chart Example Tutorial
- How to Get Last Inserted Id in Laravel 10?
- Laravel 10 Multi Auth: Create Multiple Authentication in Laravel
- How to Get Current Full URL in Laravel 10?
- Laravel 10 Socialite Login with Google Account Example
- Laravel 10 REST API with Passport Authentication Tutorial
- Laravel 10 Change Date Format Examples
- Laravel 10 REST API Authentication using Sanctum Tutorial
- Laravel 10 Ajax Form Validation Example Tutorial
- Laravel 10 React JS Auth Scaffolding Tutorial
- Laravel 10 Eloquent Mutators and Accessors Example
- Laravel 10 Create Custom Helper Functions Example
- Laravel 10 Import Export Excel and CSV File Tutorial
- Laravel 10 Generate PDF File using DomPDF Example