Laravel中的ErrorException未定义变量 [英] ErrorException in Laravel Undefined variable

查看:149
本文介绍了Laravel中的ErrorException未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel的新手,现在正在使用关系",但由于

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

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

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

控制器在usersController.php

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

路由是在 web.php

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

模型是 User.php Role.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');
    }
}

,这是用户文件夹中的 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>

错误在$users variable

推荐答案

错误的代码部分是compact($users),它必须是compact('users').固定代码为

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

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

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

这篇关于Laravel中的ErrorException未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆