0

I use Laravel 5.6.

I need to assign TWO DIFFERENT middleware in a controller with a same method but different REQUEST method (post and put).

I know it can be assigned in route/web.php.

But I just wondering is there any way to solve this issue in ONLY CONTROLLER?

This is the code below

namespace App\Http\Controllers\Users;

use Illuminate\Http\Request;
use App\Http\Controllers\Admin\Auth\AuthPagesController;

class Users extends AuthPagesController
{
    //
    public function __construct()
    {
        //this middleware should be for POST request
        $this->middleware('permission:User -> Add Item')->only('save'); 

        //this middleware should be for PUT request
        $this->middleware('permission:User -> Update Item')->only('save'); 
    }

    public function save(Request $req, $id=null){

        if ($req->isMethod('post')){

             //only check for middleware 'permission:User -> Add Item'
             //then run the 'Add Item' code

        }elseif($req->isMethod('put')){

             //only check for middleware 'permission:User -> Update Item'
             //then run the 'Update Item' code

        }

    }
}

But the code above will create problem for me because it will check BOTH MIDDLEWARE.

2
  • try request()->method() Commented Sep 26, 2018 at 3:05
  • 1
    I would highly recommend against authorization in a middleware. You're going to have a variety of problems when you try to get more granular. Commented Sep 26, 2018 at 3:12

1 Answer 1

1

Haha. I just solved my own problem.

Actually it is very simple. Just do like this in __construct method.

public function __construct(Request $req)
{
    //this middleware should be for POST request only
    if($req->isMethod('post')){
        $this->middleware('permission:User -> Add Item')->only('save'); 
    }

    //this middleware should be for PUT request only
    if($req->isMethod('put')){
        $this->middleware('permission:User -> Update Item')->only('save'); 
    }
}

public function save(Request $req, $id=null){

    // for security purpose, allow only 'post' and 'put' request
    if(!$req->isMethod('post') && !$req->isMethod('put')) return false;

    if ($req->isMethod('post')){

         //only check for middleware 'permission:User -> Add Item'
         //then run the 'Add Item' code

    }elseif($req->isMethod('put')){

         //only check for middleware 'permission:User -> Update Item'
         //then run the 'Update Item' code

    }

}

I hope this answer will be helpful to others. :D

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.