Php 隐式路由中的产品slug和id
我正试图通过使用Laravel的隐式绑定,找出如何使用/显示我产品的slug和我产品URL中的id 使用Php 隐式路由中的产品slug和id,php,laravel,Php,Laravel,我正试图通过使用Laravel的隐式绑定,找出如何使用/显示我产品的slug和我产品URL中的id 使用getRouteKeyName()返回产品slug我可以显示我的产品的slug,例如store.com/product/my awesome product。我还想在URL的末尾添加产品的ID,例如store.com/product/my awesome product/1 这可以通过getRouteKeyName()实现吗?或者我必须执行一个查询,通过ID和slug查找产品,如本文所示: 或
getRouteKeyName()
返回产品slug
我可以显示我的产品的slug,例如store.com/product/my awesome product
。我还想在URL的末尾添加产品的ID,例如store.com/product/my awesome product/1
这可以通过getRouteKeyName()
实现吗?或者我必须执行一个查询,通过ID和slug查找产品,如本文所示:
或者也可以忽略产品slug,但仍保留在url中?laravel github问题中存在一个已解决的问题,但是您可以尝试以下方法:
Route::get('products/{product:slug}', 'ProducController@show')->name('product.show'); // Finds product by slug.
Route::get('products/{product}', 'ProducController@show')->name('product.show'); // Finds Product by ID (or whatever is defined in getRouteKeyName()).
route('product.show', $product) -> store.com/product/my-awesome-product
route('product.show', $product) -> store.com/product/1
有关更多详细信息,请检查此您可以在url中设置一个参数,该参数仅用于seo(代表性)目的,不影响控制器内部的逻辑 因此: 和内部控制器:
public function show($productId, $productName){
$product = Product::findOrFail($id);
// You can add this optional check to
// make sure product name is correct
$slug = str_slug($product->name, '-');
if(!str_contains($slug, $productName)){
abort(404);
}
return view('product')->with(compact('product'));
}
public function show($productId, $productName){
$product = Product::findOrFail($id);
// You can add this optional check to
// make sure product name is correct
$slug = str_slug($product->name, '-');
if(!str_contains($slug, $productName)){
abort(404);
}
return view('product')->with(compact('product'));
}