-1
Route::get('/pizza', function () {
    $edibles = [
        'fruits' => 'Apple',
        'beverage' => 'Milo',
        'soup' => 'Egusi',
        'drink' => 'cocacola',
    ];

    return view('pizza', $edibles);
});
@foreach ($edibles as $data)
    {{ $data }} 
@endforeach

It has been saying

Undefined ErrorException PHP 8.1.6 9.42.2 Undefined variable $edibles

lagbox
  • 48,571
  • 8
  • 72
  • 83
  • Does this answer your question? [How to pass data to view in Laravel?](https://stackoverflow.com/questions/18341792/how-to-pass-data-to-view-in-laravel) – ManojKiran A Dec 15 '22 at 06:26

4 Answers4

1

Change this

return view('pizza', $edibles);

To this

return view('/pizza', compact('edibles'));
Xun
  • 377
  • 1
  • 7
1

There is two way to send backend data to front end.

  1. Without compact function you can send variable and its data as single variable name Here you can set a key name of passing data like ediblesData and get on front side with same name inside foreach loop.

Ex: return view('pizza', ['edibles' => 'edibles']);

  1. With compact function you can send variable and its data as single variable name Here you cannot set a key name of passing data and you need to get same key name on front end side.

Ex: return view('pizza', compact('edibles'));

NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
0
Route::get('/pizza', function(){
         $edibles = [
            'fruits' => 'Apple',
            'beverage' => 'Milo',
            'soup' => 'Egusi',
            'drink' => 'cocacola',
        ];
        return view('pizza', compact('edibles'));
    });
ket-c
  • 211
  • 1
  • 10
  • **compact()** takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively. reference https://www.php.net/manual/en/function.compact.php – ket-c Dec 13 '22 at 08:15
  • So if you wish to send variable to a view, you should use **compact ()** & you'll have to remove the $ sign. – ket-c Dec 13 '22 at 08:17
  • Please add some verbiage to the changes proposed in your solution. Just the snippet doesn't catch eyes of the readers on what exact changes/fix are/is proposed – Sushant Pachipulusu Dec 15 '22 at 08:43
0

You can use compact to send the data. Try this for your case:

return view('pizza', compact('edibles'));
kaann.gunerr
  • 170
  • 1
  • 13