Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nanadjei2's avatar

error Undefined variable: users when returning all users from my DB to the view

i want to return all users in my database to the view but i keep getting the error Undefined variable: users (View: C:\xampp\htdocs\AjaxLav5.0\resources\views\pages\searchUsers.blade.php)

This is my Controller

 public function allUsers() {
    $users = User::all();
    //return $users;
    return view('pages.searchUsers')->with('users', $users);
 }

This is my blade

@if (count($users) > 0)
    @foreach($users as $user)
        {{$user->name}}
    @endforeach
@endif
0 likes
8 replies
rdelorier's avatar

If you dd your users in the controller is it a collection?

Going to need a little more info, this looks fine.

nanadjei2's avatar

check my code above again. it looks fine now. but it still does not work. when i return $users, it displays them nicely in a json responds but in my view, it does not work

rdelorier's avatar

Is that the entire view ( not a partial that was included or anything)?

rdelorier's avatar

maybe....

return view('pages.searchUsers', compact('users'));
RomainLanz's avatar

Do you still have the error or you just have blank screen?

Please or to participate in this conversation.