Search code examples
phplaravelcontrollermiddleware

Laravel - Assign Middleware to specific method with specific request method in controller


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.


Solution

  • 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