Laravel 5.4:如何通过中间件将模型对象传递给控制器​​?

Pra*_*ant 4 laravel laravel-5 laravel-middleware

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

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

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

我的中间件代码是:

<?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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器中获取它,如下所示:

$request->get('bookingInstance')

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

Chr*_*win 5

您只能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);
}
Run Code Online (Sandbox Code Playgroud)

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

$request->booking = $booking;
Run Code Online (Sandbox Code Playgroud)

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