Laravel 未定义变量中的 ErrorException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51158554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:51:59  来源:igfitidea点击:

ErrorException in Laravel Undefined variable

phplaravel

提问by Stranger

I am new to Laravel and I am using Relations now, but I am getting an error as

我是 Laravel 的新手,我现在正在使用关系,但我收到一个错误

ErrorException :Undefined variable: users (View: D:\Softwares\WampServer\www\LaravelRelations\resources\views\users\index.blade.php)

ErrorException :未定义变量:用户(视图:D:\Softwares\WampServer\www\LaravelRelations\resources\views\users\index.blade.php)

Controller is inusersController.php

控制器在usersController.php

public function index()
{
    $users = \App\User::all();
    return view('users.index', compact($users));
}

Route is defined inweb.php

路线定义在web.php

Route::resource('users', 'usersController');

Models areUser.phpandRole.phpas

模型是User.phpRole.php作为

<?php
//User.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function role() {
        return $this->belongsTo('\App\Role');
    }
}


<?php
//Role.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function user() {
        return $this->hasMany('\App\User');
    }
}

and here's theindex.blade.phpin users folder as

这是index.blade.php在用户文件夹中

<!DOCTYPE html>

<html>
    <head>
        <title></title>
    </head>
    <body>
        <ul>
            <?php
                foreach ($users as $user) {
                    echo "<li>" . $user->username . "is" . $user->role->role_name;
                }
            ?>
        </ul>
    </body>
</html>

The error is in this line foreach ($users as $user) {in $users variable

该错误是在此行foreach ($users as $user) {$users variable

回答by Davit

Wrong part of your code is compact($users)It must be compact('users'). Fixed code is

代码的错误部分是compact($users)It must be compact('users')。固定代码是

public function index()
{
    $users = \App\User::all();
    return view('users.index', compact('users');
}

compact('users')is equivalent ['users' => $users]

compact('users')是等价的['users' => $users]

回答by Stranger

Try this

尝试这个

public function index()
{
    $users = \App\User::all();
    return view('users.index', ['users' => $users] );
}