【问题标题】:How to Apply Multiple Middleware in Same method on Controller in Laravel 5.4如何在 Laravel 5.4 的控制器上以相同的方法应用多个中间件
【发布时间】:2017-05-17 11:48:42
【问题描述】:

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;

class UserProfileController extends Controller
{
    public function __construct(){
       $this->middleware('auth');
       $this->middleware('auth:admin');
    }
    public function show()
    {
        return view('user.profile.show');
    }
}

在这个控制器中,我想在 show 上应用这两个中间件 方法。当我使用正常登录访问此方法时,此 显示视图的内容。但是当我使用管理员访问此方法时 登录,然后这个方法重定向到正常的登录页面。

【问题讨论】:

  • 您也可以通过路由添加中间件,并且可以设置多个中间件。您也可以在构造 $this->middleware('admin')->only('show') 中执行此操作
  • 您确定角色中间件工作正常吗?
  • 是的,但我想在控制器中使用
  • 我也在尝试这种方式 $this->middleware('auth',['only'=>['show']]); $this->middleware('auth:admin',['only'=>['show']]);
  • 但它只适用于一个中间件而不是两者

标签: php laravel laravel-5.4


【解决方案1】:

大家好

我解决了这个问题。

我只是创建一个

名为 _show() 的私有方法

这两者都通用

名为 show() 和 showAdmin() 的公共方法

auth 中间件的show() 方法

auth:admin 中间件的 showAdmin 方法

下面是我的代码。

控制器页面

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;

class UserProfileController extends Controller
{
    public function __construct(){
       $this->middleware('auth',['only'=>['show'],'only'=>['showAdmin]]);
       $this->middleware('auth:admin',['only'=>['showAdmin'],'only'=>['show]]);
    }
    public function show()
    {
        $response = $this->_show();
        //Send $response to view
    }
    public function showAdmin()
    {
        $response = $this->_show();
        //Send $response to view
    }
    private function _show()
    {
        //Common logic
        //return 
    }
}

查看页面

@if(Auth::check())
{--Goto show method via route--}
@else
{--Goto showAdmin method via route--}
@endif

我认为这对想要在 Laravel 5.4 中使用中间件的人很有帮助

谢谢

愿意尝试。它有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多