1

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

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

Controller is in usersController.php

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

Route is defined in web.php

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

Models are User.php and Role.php as

<?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

<!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

2 Answers 2

4

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') is equivalent ['users' => $users]

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah! it worked like a charm and output came, but the role is not coming up username comes but the role in not coming can u see the error? echo "<li>" . $user->username . "is" . $user->role->role_name; in this line
your role table has role_name column, and can show role table structure??
in blade after foreach ($users as $user) { dd($user->toArray());, and show result
Yeah, I understand the error was in the column name there was only name not role_name now I changed that and worked, Thanks bro! Must be accepted and again Thanks!
there's a typo in return view('users.index', compact('users'); should be return view('users.index', compact('users'));
1

Try this

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

1 Comment

The error was in compact($users) the $ sign I corrected that, Thanks for replying!