【问题标题】:Laravel Model binding including SoftDeleted valuesLaravel 模型绑定,包括 SoftDeleted 值
【发布时间】:2017-12-11 18:05:26
【问题描述】:

我有一个 Route::resource('sheeps', 'SheepsController') 带有一个返回资源的显示函数:

public function show(Sheep $sheep)
{
    return new SheepResource(
        $sheep->load('farm')
    );
}

所以当我打电话给/api/sheeps/123 时,我应该得到Sheep 123,但是...我不明白,因为它已软删除。 如何修复它也在软删除结果中搜索的资源?

【问题讨论】:

  • 不幸的是,隐式模型绑定有其局限性......正如其他人将/已经指出的那样,您可能不得不怀疑explicit model binding 来处理这个问题,因此您可以自定义解析逻辑该绑定(添加withTrashed

标签: laravel laravel-5


【解决方案1】:

你应该使用这个:

在您的 RouteServiceProvider 中:

/**     
* Define your route model bindings, pattern filters, etc.
*
 * @return void
 */
public function boot()
{


    parent::boot();

    Route::bind('sheep', function ($value) {
        return Sheep::withTrashed()->find($value);
    });



}

【讨论】:

  • 到目前为止,这是我发现的最好方法,您也可以在模型中禁用 softDelete Scope,但在我看来,它使整个 softDelete 事情变得无关紧要。实际上,我在这里有一个未解决的问题:stackoverflow.com/questions/47749901/… :)
【解决方案2】:

试试这个:

public function show($id)
{
    $sheep = Sheep::withTrashed()->findOrFail($id);

并更新您的路线 或

public function show(int $sheep)
{
    $sheep = Sheep::withTrashed()->findOrFail($sheep);

或 使用Explicit Binding

【讨论】:

  • 我对同一个答案投了两次反对票。很好的逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2018-11-26
  • 2013-11-02
  • 2018-10-27
  • 2021-05-24
  • 2020-09-22
  • 2013-05-28
相关资源
最近更新 更多