【问题标题】:Route model binding in controller@index?在控制器@索引中路由模型绑定?
【发布时间】: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()-&gt;parameters['customer'] 访问控制器逻辑中的客户 ID,但没有更好/更简单的方法吗?

【问题讨论】:

  • 你能在CustomerContactsController@index分享你的代码
  • 啊!在这里,我在想控制器出了点问题!在提供视图代码时,我意识到 contacts/index.blade.php 视图缺少 @extends ('layout') :( :(
  • 你试过dd($contacts)。实际上,只需检查您是否获取数据?

标签: laravel route-model-binding


【解决方案1】:

{customer} 参数提供给控制器的index() 方法是正确的方法。在发布这个问题后,我偶然发现了 nested resource controller 这个术语,正是描述了我想要完成的任务。在php artisan make:controller 命令的帮助消息中,我发现-p 标志会为我执行此操作。

我使用php artisan make:controller --model=Contact --parent=Customer TestCustomerContactsController 创建了一个新控制器,并发现我当前控制器的唯一更改是我已经对现有控制器进行的更改

Laravel 内置的调试屏幕是一条红鲱鱼。如果没有将$customer 限定在该方法的范围内,Laravel 将返回一个错误(应该如此)。正确设置变量范围后,错误消息消失了,但在完全空白的画布上,感觉就像我完全走错了方向。

修复

我的view 充满了@sections,但没有@extends 告诉它要渲染到哪个布局模板。如果不提供此指令,@section 块中的任何代码都不会被渲染,在我的例子中是整个视图,返回一个空页面。

回答另一个问题

如果从@Developer 的answer 中不清楚,Route URI 中的任何{parameter} 也可以通过控制器中的request()-&gt;parameter 获得。例如

// routes/web.php
Route::get('/customers/{customer}/contacts/{contact}', 'CustomerContactsController@show');

// CustomerContactsController.php
public method show()
{
    $customer_id = request()->customer;
    $contact_id = request()->contact;
}

【讨论】:

    【解决方案2】:

    如果你从控制器中获得价值,试试这个

    你的路线是

    Route::get('/customers/{customer}/contacts', 'CouponsController@testing');
    

    在你的控制器中试试这个

    public function testing(Request $req)
    {
        dd($req->customer);
    }
    

    【讨论】:

    • 没想到!虽然这不是我的问题,但为了将来记住这一点是件好事。谢谢!
    • 嗨@erich,如果您正在使用另一个并转到函数和 ' ,并像创建对象一样使用moled并在函数中获取值试试这个
    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2017-01-26
    • 2011-05-09
    • 2018-07-23
    • 2014-08-15
    • 2013-04-14
    • 2020-04-29
    相关资源
    最近更新 更多