【问题标题】:Laravel Pages with Categories Route Parameters带有类别路由参数的 Laravel 页面
【发布时间】:2016-10-06 12:40:45
【问题描述】:

基于此处的示例https://scotch.io/tutorials/simple-and-easy-laravel-routing#blog-pages-with-categories-route-parameters

我想显示特定类别的条目。 通过调用这条路线:

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

我想显示特定城市的所有条目。

这是我的控制器:

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);
}

唯一不起作用的是,通过调用带有 {city} 的 url,我想显示数据库中不存在的所有条目。 使用上面的代码不会发生这种情况。我得到一个空白页。

我该如何解决这个问题?我的猜测是我的 else 语句中的代码显示了所有条目,但事实并非如此。

【问题讨论】:

  • 你在传递一个id吗? {city}是城市ID?
  • 您是否将这条路线放入并分组,如果是,请也分享该组路线?如果还有一个路由变量,那么在您的控制器函数中,第一个变量将是组路由变量。

标签: php laravel


【解决方案1】:

执行以下操作:

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) 是问题所在。如果要获取所有文章,请删除条件。

将条件改为:

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

【讨论】:

  • 同样的结果,我只获得现有城市的条目,但如果城市不存在,则不是所有条目。
  • 我已经编辑了我的答案。另外不要忘记更改 where() 中的列以匹配您在 DB 中的列。
【解决方案2】:

使用请求 $request

 public function menue(Request $request) {
   if ($request->has('city')) {

【讨论】:

  • 仍然是没有所有条目的空白页
  • 应该是$request->has('city') :)
【解决方案3】:

我会这样做:

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

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

【讨论】:

  • 这在很多层面上都是错误的。特别是,因为您执行的查询比需要的多。
  • @IvankaTodorova 好的。我只是误解了这个问题。
猜你喜欢
  • 2017-04-29
  • 2017-10-21
  • 2017-07-10
  • 2018-08-31
  • 2015-04-17
  • 2016-01-20
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多