我正在努力使我的网址seo友好。我希望url是http://www.example.com/products/asus-zenfone-4-5649。我正在使用以下代码。但是它不能正常工作。
在我的routes.php中,Route::get('/products/{name}-{id}', 'ProductController@showProduct');
在我的控制器中,
public function showProduct($name, $id)
{
echo $name;
echo $id;
}
如果url是http://www.example.com/products/motoe-5649,它显示
$name = motoe
$id = 5649 ---> Working fine
如果url是http://www.example.com/products/asus-zenfone-4-5649,它显示
$name = asus
$id = zenfone-4-5649 ---> Not working properly
注意:不要使用like.
Route::get('/products/{name}/{id}', 'ProductController@showProduct');
我如何解决相同的问题?
这个Route::get('/products/{name}-{id}', 'ProductController@showProduct');
只需要两个参数。一个命名为name
,在/products/
之后,在-
之前,一个命名为id
,在-
之后。因此,无论-
包含多少个,-
之后存在的都被认为是id
参数。
如果你想使用更多的参数,那就把它们添加到你的路由和控制器的方法声明中。如果你有可选参数,请在它们旁边加上问号,让它们在你的路由中成为可选参数,并在你的方法中将默认值赋为null。
路线:
Route::get('products/{name}-{id}-{parameter1?}-{parameter2?}, ['as' => 'products', 'uses' => 'ProductController@showProduct']);
控制器的方法:
public function showProduct($name, $id, $parameter1 = null, $parameter2 = null)
{
return $name.$id.$parameter1.$parameter2;
}
调用路线:
{{route('products', ['aName', 'anId'])}}
或
{{route('products', ['anotherName', 'anotherId', 'aParameter1', 'aParameter2'])}}
都可以工作。当然,每个url会给出不同的url