Monday, March 20, 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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ListController extends Controller
{

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

        return view('welcome', ['names' => $names]);
    }
}

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

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">API DOCUMENTATION</div>
                <div class="panel-body">

                    @foreach ($names as $n)
                    <p></p>
                    @endforeach

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Then, added the appropriate route for it (routes.php)

<?php

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

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