为了账号安全,请及时绑定邮箱和手机立即绑定

未定义的变量即使定义了 Laravel

未定义的变量即使定义了 Laravel

PHP
牛魔王的故事 2021-11-13 19:01:44
所以我得到这个错误 Undefined variable: games 即使我的变量是在控制器中定义的:我的控制器: public function openingPage($id) {      $this->getCaseData($id);      $this->getGames();      return view('caseopener', ['cases' => $this->data])->with('games',$games);;    }    private function getCaseData($id) {        $items = DB::table('cases')->where('id', $id)->get();        $data = @$items[0] ? $items[0] : array();        if(isset($data->items)) {            $data->items = json_decode($data->items, true);        }        $this->data = $data;    }   private function getGames() {      $games = array();      foreach ($this->data->items as $item) {          $game = new Game($item);          $games[] = array(            'id' => $game->id,            'name' => $game->name,            'image' => $game->image,          );      }      return $games;  }问题似乎来自 getGames() 函数我的刀片:@for ($i = 0; $i < 10; $i++)                      <div class="item" style="background-image:url({{ $games->image }})">            </div>          @endfor如果需要,这里是我的模型“游戏”,用于该 getGames() 函数class Game extends Model{  private $id;  public $data;  public function __construct($id) {       parent::__construct();       $this->id = $id;       $this->data = $this->getData();   }   private function getData() {       $game = DB::table('products')->where('id', $this->id)->first();       if(empty($game)) return array();       return $game;   }}
查看完整描述

2 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

你忘了分配$gamesin openingPage(),试试这个:


public function openingPage($id) {


     $this->getCaseData($id);


     $games = $this->getGames();


     return view('caseopener', ['cases' => $this->data])->with('games',$games);;

}


查看完整回答
反对 回复 2021-11-13
?
呼唤远方

TA贡献1856条经验 获得超11个赞

您忘记将游戏分配给$games变量。


此外,输出值时有一个错误:$games->image应该是$games[$i]['image']。(访问特定游戏并获取image值作为数组值)


如果将来有可能会有多于或少于 10 场比赛,我会将for循环替换为foreach:


@foreach($games in $game)

    <div class="item" style="background-image:url({{ $game['image'] }})">

    </div>

@endforeach


查看完整回答
反对 回复 2021-11-13
  • 2 回答
  • 0 关注
  • 90 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信