【问题标题】:laravel - passing more than one list to a viewlaravel - 将多个列表传递给视图
【发布时间】:2014-03-11 01:24:15
【问题描述】:

我有一个联赛列表,我要传递到这样的视图...

$leagues = League::lists('name', 'id');
return View::make('gameworlds.create')->with('leagues', $leagues);

我想做的是传递另一个列表,例如国家/地区,但我不确定该怎么做。

例如

$leagues = League::lists('name', 'id');
$countries = Country::lists('name', 'id');
return View::make('gameworlds.create')->with('leagues', $leagues ... ... ... );

请问我怎样才能追加 $countries? 我已经看到将 $data 创建为一个数组,但同样不完全确定如何设置它。

有人可以建议吗?

DS

【问题讨论】:

    标签: php laravel laravel-4 blade


    【解决方案1】:

    很简单,只需添加多个“with”元素:

    $leagues = League::lists('name', 'id');
    $countries = Country::lists('name', 'id');
    return View::make('gameworlds.create')->with('leagues', $leagues)->with('countries', $countries);
    

    【讨论】:

    • 我已将此标记为答案,因为它对我来说最直观……“只需为您要添加的每件事添加一个 with”-谢谢大家-我会的充分调查其他答案以了解我的选择。非常感谢大家。
    【解决方案2】:

    你可以这样做

     $leagues = League::lists('name', 'id');
     $countries = Country::lists('name', 'id');
     $data['leagues'] = $leagues;
     $data['countries'] = $countries;
     return View::make('gameworlds.create')->with($data);
    

    与trizz 所说的相反,您可以从数组索引的名称访问视图中的变量。 意味着您可以通过 $leagues / $countries 访问它们,例如使用多个 with 语句

    【讨论】:

    • 我的错。我已经改变了我的答案:)
    • 我会评论你的答案而不是做出类似的回应,但评论需要 50 声望
    【解决方案3】:
    return View::make('gameworlds.create')->with(array('leagues'=>$leagues,'countries'=> $countries));
    

    【讨论】:

      【解决方案4】:

      所有这些答案都是正确的,但没有人给你最好、最简单、最易读的版本:

      // get data
      $leagues = League::lists('name', 'id');
      $countries = Country::lists('name', 'id');
      
      // render view and pass data in
      return View::make('gameworlds.create', compact('leagues', 'countries'));
      

      需要考虑的事项:

      • PHP 的compact 函数是非常有用的语法糖
      • 我更喜欢将数据作为View::make() 的第二个参数传递给我的视图,但您仍然可以使用->with(compact(...)) 执行此操作

      【讨论】:

      • 我会更多地研究这个紧凑的功能 - 我没有将它标记为答案,因为在这种情况下我使用了不同的解决方案。非常感谢您的帮助
      【解决方案5】:

      你可以试试这个

      return View::make('gameworlds.create')
                 ->with('leagues', $leagues)
                 ->with('countries', $countries); // more withs could be added
      

      或者这个也可以

      $array = array('leagues' => $leagues, 'countries' => $countries);
      return View::make('gameworlds.create', $array);
      

      或者使用快捷方式array语法

      return View::make('gameworlds.create', ['leagues' => $leagues, 'countries' => $countries]);
      

      或使用compact

      $leagues = League::lists('name', 'id');
      $countries = Country::lists('name', 'id');
      return View::make('gameworlds.create', compact('leagues', 'countries'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-21
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-06
        相关资源
        最近更新 更多