如何在 Laravel 5 中实现“where slug()”?

Dav*_*vid 1 php laravel

我想映射这种类型的路线:

/images/united-states/san-francisco
Run Code Online (Sandbox Code Playgroud)

在我的routes.php文件中,我写道:

Route::get('/images/{country_slug}/{city_slug}', 'ImageController@listByCountryAndCity');
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

public function listByCountryAndCity($country, $city)
{
    return Image::where('country', $country)->where('city', $city)->paginate();
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能一决高下国家比较过吗?

而且我不想添加任何其他名为CountryCity 的

Mus*_*00m 6

在像你这样的情况下,我会做这样的路线:

Route::get('/post/{id}-{slug}', 'PostController@show');
Run Code Online (Sandbox Code Playgroud)

在您的控制器中:

public function show($id, $slug)
{
    return Post::find($id);
}
Run Code Online (Sandbox Code Playgroud)

所以 slug 只是为了 SEO 而你只使用 $id

或者,您可以创建一个范围:

public function scopeFindBySlug($query, $title)
{
    $query->where('slug', '=', str_slug($title));
}

Post::findBySlug($title)->first();
Run Code Online (Sandbox Code Playgroud)