[英]ErrorException in Laravel Undefined variable
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 in usersController.php
控制器位于 usersController.php
public function index()
{
$users = \App\User::all();
return view('users.index', compact($users));
}
Route is defined in web.php
路线在 web.php
定义
Route::resource('users', 'usersController');
Models are User.php
and Role.php
as 模型是 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');
}
}
and here's the index.blade.php
in 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
Wrong part of your code is compact($users)
It must be compact('users')
. 代码的错误部分是compact($users)
它必须是compact('users')
。 Fixed code is 固定代码为
public function index()
{
$users = \App\User::all();
return view('users.index', compact('users');
}
compact('users') is equivalent ['users' => $users] compact('users')是等效的['users'=> $ users]
Try this 尝试这个
public function index()
{
$users = \App\User::all();
return view('users.index', ['users' => $users] );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.