Laravel中间件将变量返回给控制器 [英] Laravel Middleware return variable to controller

查看:103
本文介绍了Laravel中间件将变量返回给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对用户进行权限检查,以确定他们是否可以查看页面.这涉及到首先通过一些中间件传递请求.

I am carrying out a permissions check on a user to determine whether they can view a page or not. This involves passing the request through some middleware first.

我遇到的问题是在将数据返回到视图本身之前,我正在中间件和控制器中复制相同的数据库查询.

The problem I have is I am duplicating the same database query in the middleware and in the controller before returning the data to the view itself.

以下是设置示例;

-routes.php

-- routes.php

Route::get('pages/{id}', [
   'as' => 'pages',
   'middleware' => 'pageUser'
   'uses' => 'PagesController@view'
]);

-PageUserMiddleware.php(PageUserMiddleware类)

-- PageUserMiddleware.php (class PageUserMiddleware)

public function handle($request, Closure $next)
    {
        //get the page
        $pageId = $request->route('id');
        //find the page with users
        $page = Page::with('users')->where('id', $pageId)->first();
        //check if the logged in user exists for the page
        if(!$page->users()->wherePivot('user_id', Auth::user()->id)->exists()) {
            //redirect them if they don't exist
            return redirect()->route('redirectRoute');
        }
        return $next($request);
    }

-PagesController.php

-- PagesController.php

public function view($id)
{
    $page = Page::with('users')->where('id', $id)->first();
    return view('pages.view', ['page' => $page]);
}

如您所见,在中间件和控制器中都重复了Page::with('users')->where('id', $id)->first().我需要将数据从一个传递到另一个,以免重复.

As you can see, the Page::with('users')->where('id', $id)->first() is repeated in both the middleware and controller. I need to pass the data through from one to the other so an not to duplicate.

推荐答案

我相信(在Laravel 5.x中)执行此操作的正确方法是将自定义字段添加到attributes属性.

I believe the correct way to do this (in Laravel 5.x) is to add your custom fields to the attributes property.

从源代码注释中,我们可以看到属性用于自定义参数:

From the source code comments, we can see attributes is used for custom parameters:

 /**
 * Custom parameters.
 *
 * @var \Symfony\Component\HttpFoundation\ParameterBag
 *
 * @api
 */
public $attributes;

因此,您可以按以下方式实现此目标;

So you would implement this as follows;

$request->attributes->add(['myAttribute' => 'myValue']);

然后您可以通过调用以下内容来检索属性:

You can then retrieved the attribute by calling:

\Request::get('myAttribute');

或者来自laravel 5.5+中的请求对象

Or from request object in laravel 5.5+

 $request->get('myAttribute');

这篇关于Laravel中间件将变量返回给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆