所以我得到這個錯誤 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);;
}

呼喚遠方
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
- 2 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消