Add a Middleware for Only One Single Method in the Controller - Laravel

There is a middleware called ageCheck and a controller called MyController and it has following methods which is returning views.

index();
show();
edit();

How can I add a route middleware for only edit method in the MyController?

I tried this, but it doesn't work!

routes.php:

Route::get('/edit', [
  'middleware' => 'ageCheck',
  'MyController@edit'
]);

2 Answers

You can add it at the end of the route that you define:

Route::get('/edit', 'MyController@edit')->middleware('ageCheck');

Documentation

Another option would be to put it in the construct of your class:

class Mycontroller {

    public function __construct() {
        $this->middleware('ageCheck')->only('edit');
    }

Documentation

if you using laravel 5.3 and greater. try this

 Route::get('/edit','MyController@edit')->middleware('ageCheck');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest