Laravel 依赖注入不工作

Laravel dependency injection not working

我在我的 laravel 应用程序中使用资源控制器,我正在尝试使用依赖注入,但它不适用于特定模型和控制器。

这个有效:

/**
* Display the specified resource.
*
* @param  \App\Booking  $booking
* @return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
    return $booking;
}

但出于某些令人气愤的原因,这并没有:

/**
 * Display the specified resource.
 *
 * @param  \App\SchoolEvent  $schoolEvent
 * @return \Illuminate\Http\Response
 */
public function show(SchoolEvent $schoolEvent)
{
    return $schoolEvent;
}

我的路线是这样的:

// Events
Route::resource('events', Resources\SchoolEventController::class);

// Bookings
Route::resource('bookings', Resources\BookingController::class);

出于某种原因 /bookings/1 returns 一个填充对象,但 /events/1 returns 一个空对象。谁能告诉我为什么?

将模型名称更改为 Event 以使 model binding 生效。

Since the $user variable is type-hinted as the App\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI

将注入的变量名改为$event以匹配路由参数名{event}:

public function show(SchoolEvent $event)

您可以使用此命令查看路由参数:

php artisan route:list

还有另一种可能的解决方案。

如前所述Laravel 尝试注入实例,但 URI 段名称与变量不匹配。

Laravel 允许在 boot() 方法中将模型显式绑定到 RouteServiceProvider 中的 slug。

你的情况:

public function boot()
{
   parent::boot();

   // binds the slug event to our SchoolEvent model
   Route::model('event', \App\SchoolEvent::class);
}

参见:https://laravel.com/docs/5.4/routing#explicit-binding

我觉得这两种方案都可行,但个人更喜欢这一种。所有非默认的 slug 都在一个地方,而不是在单独的控制器中,我一直使用 artisan 来快速生成基本的控制器代码。

当您使用 Route::resource 时,这将自动生成所有路由以及进入每个路由的参数的名称。

要知道名字是什么,运行 php artisan route:list 在您的终端。之后,您将看到每条路线正在等待的名称。在您的控制器中使用此名称。

在你的情况下,可能是 $school_event.

如果你不喜欢这个名字,你可以使用这样的参数函数:

Route::resource(**'events'**, Resources\SchoolEventController::class)
    ->parameters([
        **'events'** => 'here_the_name_you_want'
]);

继续Laravel 5.5!

参考:https://laravel.com/docs/5.5/controllers#restful-naming-resource-route-parameters