J'essaye d'utiliser une boucle insinde laravel return view () pour passer plusieurs variables. Ainsi, pas besoin de les coder en dur et cette liste contient 30 éléments et sélectionne toujours 8 valeurs au hasard. Voici donc mon code
return view ( 'shop.landing' , [
for($z = 0 ; $z <8 ;$z++){
'productMatchesToMasterCategory' => ($masterCategoryList[$z]['name'].$productMatchesToMasterCategory);
}
'tomorrow' => Carbon::tomorrow () ,
C'est le cliché
Quelqu'un pourrait-il dire ce qui ne va pas? dans mon code ou est-il interdit d'utiliser une boucle à l'intérieur de view()?
Merci
3 Réponses :
Vous ne pouvez pas utiliser une boucle à l'intérieur de la syntaxe de tableau. La solution consiste à créer le tableau à l'extérieur, puis à le transmettre en tant que paramètre. Je ne suis pas sûr de la structure que vous recherchez, mais quelque chose comme ceci:
$data = [];
for ($z = 0; $z < 8; $z++) {
$data[] = ($masterCategoryList[$z]['name'] . $productMatchesToMasterCategory);
}
return view('shop.landing', [
'productMatchesToMasterCategory' => $data,
'tomorrow' => Carbon::tomorrow(),
]);
Vous devriez le faire avant de renvoyer la vue:
$productMatchesToMasterCategoryArray = [];
for($z = 0; $z < 8; $z++) {
$productMatchesToMasterCategoryArray[] = ($masterCategoryList[$z]['name'].$productMatchesToMasterCategory);
}
return view('shop.landing', [
'productMatchesToMasterCategory' => $productMatchesToMasterCategoryArray
//Other variables here
]);
J'espère que cela vous aidera.
vous pouvez essayer d'obtenir le tableau d'éléments aléatoires 8 avant de renvoyer la vue.
$productMatchesToMasterCategoryArray = [];
foreach($masterCategoryList as $z){
$productMatchesToMasterCategoryArray[] = ($z['name'].$productMatchesToMasterCategory);
}
$random_Array=array_rand($productMatchesToMasterCategoryArray,8);
return view('shop.landing', [
'productMatchesToMasterCategory' => $random_Array,
'tomorrow' => Carbon::tomorrow(),
]);