douhu4091 2016-10-06 12:40
浏览 16
已采纳

Laravel页面与类别路由参数

based on the example from here https://scotch.io/tutorials/simple-and-easy-laravel-routing#blog-pages-with-categories-route-parameters

I want to show entries for specific categories. By calling this Route:

Route::get('menues/{city?}', 'PagesController@menue');

I want to show all entries for a specific city.

This is my Controller:

public function menue($city = null) {

  if ($city) {
    $restaurants = User::with(['articles' => function ($q){
        $q->nowpublished();
    }])->where('city', '=', $city)->get();
  } else {
    $restaurants = User::with(['articles' => function ($q){
        $q->nowpublished();
    }])->where('city', '!=', $city)->get();
  }

  return view('pages.menues')
    ->withRestaurants($restaurants) 
    ->withCity($city);
}

The only thing that doesn't work is, by calling a url with a {city} that doesn't exist in the DB I want to display all entries. With the code above this doesn't happen. I get a blank page.

How can I fix this? My guess was that the code inside my else statement displays all entries, but this isn't the case.

  • 写回答

3条回答 默认 最新

  • dtcaw02086 2016-10-06 12:48
    关注

    Do the following:

    public function menue($city = null) {
        $restaurants = User::with(['articles' => function ($q){
            $q->nowpublished();
        }]);
    
        if(if(!is_null($city) && !is_null(City::where('name', $city)->first())) {
            $restaurants->where('city', '=', $city);
        }
    
        $restaurants = $restaurants->get();
        return view('pages.menues')
            ->withRestaurants($restaurants) 
            ->withCity($city);
    }
    

    ->where('city', '!=', $city) is the problem. If you want to get all articles, remove the condition.

    Change the condition to:

    if(!is_null($city) && !is_null(City::where('name', $city)->first())

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料