【发布时间】:2019-10-22 14:07:39
【问题描述】:
我想设置一个路由来获取与Customer 关联的所有Contacts。端点看起来像/customers/{customer}/contacts 这样{customer} 提供了应返回联系人的上下文。我的routes/web.php 看起来像这样:
Route::get('/customers/{customer}/contacts', 'CustomerContactsController@index');
我生成了指定--model=Contact 的控制器。结果,一些方法带有开箱即用的类型提示,但index() 方法没有,实际上不会在提供任何参数的情况下运行。
来自CustomerContactsController.php:
public function index(Customer $customer)
{
$this->authorize('update', $customer->account);
$contacts = $customer->contacts;
return view('contacts.index', compact('customer', 'contacts'));
}
这将返回一个完全空白的屏幕。关联的 Blade 视图如下所示:
@section('title')
{{ $customer->name }}
@endsection
@section('action')
<a href="{{ $customer->path() . '/contacts/create' }}" class="button" >{{ __('Add New Contact') }}</a>
@endsection
@section('content')
<ul>
@foreach ($contacts as $contact)
<li>{{ $contact->name }}</li>
@endforeach
</ul>
@endsection
我仍然可以使用 Route::current()->parameters['customer'] 访问控制器逻辑中的客户 ID,但没有更好/更简单的方法吗?
【问题讨论】:
-
你能在
CustomerContactsController@index分享你的代码 -
啊!在这里,我在想控制器出了点问题!在提供视图代码时,我意识到
contacts/index.blade.php视图缺少@extends ('layout'):( :( -
你试过
dd($contacts)。实际上,只需检查您是否获取数据?
标签: laravel route-model-binding