沃梦达 / 编程问答 / php问题 / 正文

Laravel 中间件将变量返回给控制器

Laravel Middleware return variable to controller(Laravel 中间件将变量返回给控制器)

本文介绍了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 中)是将自定义字段添加到属性属性中.

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 SymfonyComponentHttpFoundationParameterBag
 *
 * @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 中间件将变量返回给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 中间件将变量返回给控制器

基础教程推荐