Laravel - 防止额外的字符slug参数

时间:2018-05-10 07:16:07

标签: php laravel url routes slug

我有多条路线模型绑定路线,用于指导用户购物> 类别>的产品即可。路线链接正常。

但是如果用户向URL添加垃圾值,Laravel不会抛出404错误。如果用户向URL添加任何额外字符,如何强制404错误?

路线

Route::get('/{shop_url}/{category_url}/{product_url}/buy', 'Controller@buy')->name('buy')->where(['shop_url', 'category_url', 'product_url' => '[\w\d\-]+(.*)']);

Route::get('/{shop_url}/{category_url}', 'Controller@view')->name('view')->where(['shop_url','category_url' => '[\w\d\-]+(.*)']);

Route::get('/{shop_url}', 'Controller@shop')->name('shop')->where('shop_url', '[\w\d\-]+(.*)');

控制器

public function shop($shop_url)
{
  $shop = Shop::where('shop_url', $shop_url)->firstorfail();
  return view ('shop', compact('shop'));
}

public function view($shop_url, $category_url)
{
  $shop = Shop::where('shop_url', $shop_url)->firstorfail();
  $category= Category::firstorfail();

  return view ('shop', compact('shop', 'category'));
}

public function buy($shop_url, $category_url, $product_url)

{
  $shop = Shop::where('shop_url', $shop_url)->firstorfail();
  $category= Category::where('category_url', $category_url)->firstorfail();
  $product = Product::firstorfail();

  return view ('shop', compact('shop', 'category', 'product'));
}

此处domain.com/shop-ca/clothing有效,如果用户输入domain.com/shop-ca/clothes,它也会显示相同的页面。在这里,我希望它显示404.我该怎么做?

2 个答案:

答案 0 :(得分:1)

首先,你应该检查你的slug,在你的代码中我看到这些行:

$category= Category::firstorfail();// it will get the first route in the database, not the needed category

所以,首先,尝试这样做:

public function view($shop_url, $category_url)
{
   $shop = Shop::where('shop_url', $shop_url)->firstOrfail();
   $category= Category::where('category_url', $category_url)->firstOrfail();// I actually don't know the name of your slug field, but if the category is wrong, laravel will return 404 page.

   return view ('shop', compact('shop', 'category'));
}

答案 1 :(得分:0)

您已在$product_url功能中检查buy,并手动检查404错误。