拉拉维尔 5.4 : how to pass model object to controller via middleware?

标签 laravel laravel-5 laravel-middleware

我正在 Laravel 5.4 中创建一个应用程序,其中有一个中间件 ValidateBooking ,然后是一个使用 /booking/6/car 等 URL 调用的 Controller ,其中列出了分配给该预订的所有汽车。

ValidateBooking 中间件中,我使用 Booking::find(6) Eloquent 验证上述 URL 中的预订 ID 6功能。但我想要的是,如果 Booking 存在,则将该对象传递给 Controller ​​,这样我就不会在 Controller 中再次获取它。我不想为同一件事查询数据库两次。

我尝试了几种方法将模型对象与中间件中的 $request 合并,但无法在 Controller 中正确访问它。

我的中间件代码是:

<?php

namespace App\Http\Middleware\Booking;

use Closure;
use App\Booking\Booking;

class ValidateBooking
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $booking = Booking::find($request->booking_id);
        if (!$booking) {
            return redirect(route('booking.show', $request->booking_id));
        }
        $request->attributes->add(['bookingInstance' => $booking]);
        return $next($request);
    }
}

然后在 Controller 中获取它,如下所示:

$request->get('bookingInstance')

如果我传递任何字符串值或其他内容,但不是对象,它会起作用吗?请告知最好的方法是什么。

最佳答案

您只能在请求对象上使用 merge() 函数。

public function handle($request, Closure $next)
{
    $booking = Booking::find($request->booking_id);
    if (!$booking) {
        return redirect(route('booking.show', $request->booking_id));
    }
    $request->merge(['bookingInstance' => $booking]);
    return $next($request);
}

除了使用已被证明有效的 $request->merge() 之外,只需使用以下命令将模型对象添加到请求中也可以帮助您访问 Controller 中的模型:

$request->booking = $booking;

唯一需要注意的是确保永远不存在名为 booking 的参数,以免覆盖它。

关于拉拉维尔 5.4 : how to pass model object to controller via middleware?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397458/

相关文章:

php - Laravel 5.2 - 使用字符串作为 Eloquent 表的自定义主键变为 0

Laravel - 将变量从中间件传递到 Controller /路由

php - Laravel 服务类在没有服务提供者的情况下也能工作吗?

php - Laravel 4 - 如何插入多个模型?

php - 我的一个迁移没有在 Laravel 4 中使用 php artisan 命令运行

laravel-5 - Laravel guest 中间件

php - 拉维尔 5 : Call method in class before the method indicated by the route

php - 如何在 Laravel 中同步同一个属性的多个值?

php - 带有 Twig 的 laravel csrf token

php - Laravel 4/5 搜索表单,如