2017-05-05 12:17
浏览 492


as the title says I want to use a middleware inside a controller function. I have resource controllers, which their functions inside will have different access rights so I can't use a middleware in the web.php file, I have to use or apply it separately in each function to limit access, my googling hasn't been successful in getting a solution to that so far. Any help please and thanks in advance.

P.S. I believe no code is necessary here.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doudou5023
    doudou5023 2017-05-05 12:43

    Middleware could also be applied to just one function, just add the method name in your controller constructor

    public function __construct()
        // Middleware only applied to these methods
        $this->middleware('loggedIn', ['only' => [
            'update' // Could add bunch of more methods too

    Here's the documentation

    点赞 评论
  • duanbo7517
    duanbo7517 2017-05-05 12:20

    Use the following code inside your controller constructor. The following code will use the auth middleware:

    public function __construct() {
    点赞 评论
  • dpxw7293
    dpxw7293 2017-06-28 16:29

    Also you can simply add middleware at your routes. For example I need to add middleware for my method "registration_fee()" inside "RegisterController", so it will looks like this:

    Route::get('/pay_register_fee', 'Auth\RegisterController@registration_fee')
    ->name('pay_register_fee')->middleware(['guest', Register::class, RegistrationFee::class]);

    "RegistrationFee" is middleware that I want to add.
    P.S. Not forget import class or write full path to middleware.

    点赞 评论