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...
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');
Another option would be to put it in the construct of your class:
class Mycontroller {
public function __construct() {
$this->middleware('ageCheck')->only('edit');
}
if you using laravel 5.3 and greater. try this
Route::get('/edit','MyController@edit')->middleware('ageCheck');