duanduan8439 2018-09-26 02:48
浏览 135

Laravel - 使用控制器中的特定请求方法将中间件分配给特定方法

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.

  • 写回答

1条回答 默认 最新

  • drmticpet66231422 2018-09-26 03:42
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥150 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装