2017-06-04 114 views
2

我已经实现路径模型,结合如下:Laravel 5.4 - 路径模型,绑定条件

路线:

Route::get('property/{property}', '[email protected]'); 

控制器:

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

    return view('property.view', $data); 
} 

这个伟大的工程。不过,我想向Property模型添加一个条件来检查active = 1。我如何以及在哪里做这件事?

+1

你有什么试过的?你基本上是问如何使用if语句... – sisve

+0

有没有办法在模型中做到这一点,而不是控制器? – GSTAR

+0

该文档提到了显式绑定;这会为你工作吗? https://laravel.com/docs/5.4/routing#explicit-binding – sisve

回答

0

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

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

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