Laravel Middleware return variable to controller(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 中间件将变量返回给控制器
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01