Laravel 7.x Middleware with Parameters Example

Hey Artisan

In this tutorial i will show you step by step how to pass parameter to middleware. In this tutorial we will see how we can pass multiple parameter to middleware also. In this laravel middleware parameters example tutorial we can also learn how we can create custom middleware and how we can use it.

If you don't know how to create custom middleware and how to use it, you are a right place. In this tutorial we will create custom middleware and we can pass parameter to it. We can also pass multiple parameter in controller, we will also see it.

For this laravel middleware with parameter tutorial, i will create a user subscription plan. It could be monthly or yearly. Who have this plan who only access this specific page or subscription page.

laravel-middleware-with-parameter

 

Let's try how we can create this mechanism and passing parameter to middleware. You read also this below tutorial.

Read aslo : Laravel 6 Middleware Tutorial With Example

 

Step 1: Creating Migration

For creating a subscription plan to user, open user table and add the following code.

Schema::create('users', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('email',191)->unique();
  $table->enum('plan',['monthly','yearly'])->nullabel();
  $table->timestamp('email_verified_at')->nullable();
  $table->string('password');
  $table->rememberToken();
  $table->timestamps();
});

 

And run this below command to migrate our newly created field.

php artisan migrate

 

Step 2: Creating Middleware 

To create our custom middleware, run this below command.

php artisan make:middleware SubscriptionMiddleware

 

Step 3 : Register Middleware 

Now we want to call middleware using a name like "tom or ben ten". For this we have to register our middleware inside Kernel.php file. so open it and paste this following code.

app/Http/Kernel.php

 protected $routeMiddleware = [
       .
       .
       .
       'test' => \App\Http\Middleware\SubscriptionMiddleware::class,
];

 

After successfully done all of those thing then we have to create our route to check it.

Step 4: Create Route

Now paste this below code to your web.php file.

routes/web.php

Route::get('/login','[email protected]');

Route::middleware(['test:monthly'])->group(function () {
   
    Route::get('/test','[email protected]');

});

 

Here test is our middleware name and monthly is our parameter. you can pass multiple parameter just using comma sign like that.

Route::middleware(['test:monthly,one,two,three'])->group(function () {
   
    Route::get('/test','[email protected]');

});

 

Here one, two, three all of our parameter name. Hope you got it.

Step 5: Add Controller Method

Now at last we have to add new controller method inside TestController.php file. So let's add index() method on TestController.php file.

app/Http/Controllers/TestController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index()
    { 
      \App\User::truncate();

      $user = \App\User::create([
        'name' => 'JohnDoe',
        'email' => '[email protected]',
        'password' => bcrypt('password'),
        'plan' => 'yearly'
       ]);

       auth()->login($user);

       return redirect('/');
    }

    public function check()
    {
        dd('You can only see this page if you are logged in and subscribe to the monthly plane');
    }
}

 

Step 6 : Setup Middleware Logic

After paste those code now time to create our logic. So open SubscriptionMiddleware and paste those below code.

app/Http/Middleware/SubscriptionMiddleware.php

namespace App\Http\Middleware;

use Closure;

class SubscriptionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param string $plan
     * @return mixed
     */
    public function handle($request, Closure $next , $plan = null)
    {   
        $user = $request->user();

        if($user && $user->subscribedToPlan($plan)) {
           return $next($request);
        }

        return redirect('/');
       
    }
}

 

Step 7 : Setup User Model

Now we have to create our subscribedToPlan method inside our User model. So open User model and paste this code.

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password','plan',
    ];

    public function subscribedToPlan($plan = null)
    {
        if( $plan ) {
            return $this->plan == $plan;
        }

        return $this->plan;
    }
}

 

Now this middleware logic will work for this route url. So now visit this login url first to create our user. So register and logge in and check this tutorial whether it is worked or not.

Now if you visit this below url, you can not access it. Beacuse we created a user of yearly plan. It will redirect you to the home url.

127.0.0.1:8000/test

 

But our middleware parameter is monthly plan. Now just replace this monthly plan to yearly and visit again, then you can see this below image.

laravel-middleware-multiple-parameter

 

Read also : How to Use Laravel Cache For Quick Load Time

 

In this tutorial, I offered an overview of controllers and middleware with single parameter or multiple parameter. If you wish to add a suggestion or have a question, do leave a comment below.Hope it can help you.