CRUD方法的全球范围

时间:2018-11-18 11:33:45

标签: php laravel

我有模型Page和全局范围active

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    static::addGlobalScope('active', function (Builder $builder) {
        $builder->where('active', true);
    });
}

当活动页面= 0时。我无法访问编辑页面并将活动页面更改为1。 在控制器中,我尝试不带GlobalScope('active')的调用函数,但不起作用。我收到404错误。

/**
 * Show the form for editing the specified resource.
 *
 * @param  \App\Page  $page
 * @return \Illuminate\Http\Response
 */
public function edit(Page $page)
{
    $page->withoutGlobalScope('active');
    return view('admin.pages.edit-add', compact('page'));
}

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

您将收到404的原因是由于路由模型绑定。从本质上讲,该应用程序正在尝试为您解析Page模型,甚至还没有进入Controller方法,如果找不到它,它将抛出404。

您应该能够通过将以下内容添加到控制器的构造函数中来解决此问题:

Route::bind('page', function ($id) {
    return Page::withoutGlobalScope('active')->find($id) ?? abort(404);
});

Documentation