未定义的变量:名称

时间:2017-03-17 14:33:50

标签: laravel laravel-5

我在将数据从Controller推送到View时遇到了困难。下面是我的代码脚本。

我使用ListController

创建了我的控制器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]);
    }
}

创建了一个视图welcome.blade.php(默认设置)

@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>{{$n}}</p>
                    @endforeach

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

然后,为它添加了适当的路线(routes.php)

<?php

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

在运行localhost:8000后打开php artisan serve时,会抛出异常

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

到目前为止,我尝试过以下方法: 在控制器中:

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

在视图中对数组进行硬编码并为其赋值变量

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

我似乎无法发现问题。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

您应该使用数组传递变量:

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

或者只是:

return view('welcome', compact('names'));

要检查它是否在视图中执行此操作:

{{ dd($names) }}

答案 1 :(得分:0)

首先,按照Alexey的说法传递你的变量,

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

然后,在视图中,执行

@foreach ($names as $n) <p>This is name {{ $n }}</p> @endforeach

此处的文档:https://laravel.com/docs/master/blade#displaying-data

答案 2 :(得分:0)

管理以解决此问题。 花了这么多时间寻找bug之后,我试着检查一下laravel版本是否与此有关。 routes.php Laravel v5.3+无法使用Laravel v5.4.x,我使用routes

路由位于名为routes.php的目录中,因此我将代码从routes/web.php粘贴到<?php Route::get('/', 'ListController@listNames'); 粘贴了

SELECT *
FROM Books
JOIN Authors USING (AuthorId)