Laravel 5.4-路线模型结合条件



我已经实现了路由模型绑定如下:

路线:

Route::get('property/{property}', 'PropertyController@view');

控制器:

public function view(Property $property)
{
    $data = compact([
        'property'
    ]);
    return view('property.view', $data);
}

这很好。但是,我想在属性模型中添加条件,以检查active = 1。我该怎么做?

您可以注册显式绑定。将下面的代码添加到RouteServiceProvider。当段为 property时,这将应用于模型绑定。

Route::bind('property', function ($id) {
    return AppProperty::where('id', $id)
        ->where('active', 1)
        ->firstOrFail();
});

如果您需要为每个结果全球应用此条件,则可以添加一个全局范围。https://laravel.com/docs/5.4/eloquent#global-scopes

最新更新