:::
12. 建立商品詳情頁的路由
- 點進去某個商品,路由是連到
product/{{$product->id}},所以,在/專案/routes/web.php新增一筆路由資料Route::get('/product/{id}', 'ProductController@show')->name('product.show'); - 路徑中的
{id}可以直接在控制器中變成變數$id使用,所以,無須自己帶參數過去。不過路由的參數和控制器的變數是以先後位置來對應的,無關名稱,換言之,控制器中不命名為$id也是可以的。 - 如果該參數可有可無,那麼可以寫成
{id?}這樣的方式。 - 如果路由有參數,且確定其格式,那麼可以用
->where()限制參數格式(否則product/create中的create也可能會被當成id),例如:限制id 只允許 0~9 的數字,如此可以降低路由被誤判的機會Route::get('/product/{id}', 'ProductController@show')->name('product.show')->where('id', '[0-9]+'); - 如果同一個參數要限制格式,且有好幾個 Route 要用,則可用
Route::pattern()方式來統一宣告(記得放最上面):Route::pattern('id' , '[0-9]+'); - 最後,整個路由看起來像這樣:
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::pattern('id', '[0-9]+'); Route::get('/', 'ProductController@index')->name('index'); Route::get('/product', 'ProductController@index')->name('product.index'); Route::get('/product/{id}', 'ProductController@show')->name('product.show'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home');
11-2 建立Seeder快速填充資料
