dongxue9997 2018-10-06 12:24
浏览 262

带有多个可选参数的URL

Suppose I have page for searching cars, page takes 3 optional parameters, brand, year and color

Simplified route example:

Route::get('/cars/{brand?}/{year?}/{color?}', function ($brand = NULL, $year = NULL, $color = NULL) {

    echo "brand is:".$brand."<br>";
    echo "year is:".$year."<br>";
    echo "color is:".$color."<br>";

});

I don't realise how to pass for example only year parameter?

Works if passed all of 3 parameters, for example: /cars/_/2010/_ but this is very inelegant solution.

What is proper way for this ?

  • 写回答

2条回答 默认 最新

  • doulu0266 2018-10-06 13:07
    关注

    I don't know if this is possible since you may end up passing only 2 parameters and Laravel wouldn't be able to understand if this is brand, color or year.

    I will leave my two cents regarding on my method of URL parameters that I use:

    public function getCars(Request $request){
            Validator::validate($request->all(), [
                'brand' => 'nullable|string',
                'year' => 'nullable|integer',
                'color' => 'nullable|string'
            ]);
    
            $cars = Car::select('id', '...');
    
            if($request->has('brand')){
                // get cars with that brand
                $cars->where('brand', $request->brand);
            }
    
            // ... and so on with the other parameters
    
            $cars = $cars->paginate(10); // or $cars->get()
    
        }
    

    This is a fairly simple example so you will have to customize to your needs. Hope that helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退