Friday, March 17, 2017

Undefined variable: names

I am facing difficulties pushing data from the Controller to the View. Below is my code script.

I created my controller ListController using artisan

php artisan make:controller ListController

ListController - show method

public function show()
{
    $names = array(
        'Daenerys Targaryen', 
        'Jon Snow',
        'Arya Stark',
        'Melisandre',
        'Khal Drogo'
    );

    return view('welcome', $names);
}

Created a view welcome.blade.php (which is default)

<?php foreach ($names as $n):?>
<tr>
   <td><?php echo $n;?></td>
</tr>
<?php endforeach;?>

Then, added the appropriate route for it

Route::get('/', 'ListController@show');

When opening localhost:8000 after running php artisan serve, it throws an Exception

ErrorException in 56f6d37e6c39b528e3f5a170141b734befe0f7a2.php line 14:
Undefined variable: names (View: /Applications/MAMP/.../views/welcome.blade.php)

So far I have tried the following: In the Controller:

return view('welcome', compact('names'));      --> DOESN'T WORK
return view('welcome', $names);                --> DOESN'T WORK
return view('welcome')->with($names);          --> DOESN'T WORK
return view('welcome')->with('names', $names); --> DOESN'T WORK

Hard coding the array in the view and assigning it a variable works

<?php $names = array('John Snow', 'Arya Stark');?>
<?php foreach ($names as $n):?>
<tr>
    <td><?php echo $n;?></td>
</tr>
<?php endforeach;?>

I can't seem to detect the problem. Any help is appreciated.



via h4kl0rd

Advertisement