0

I have been having a problem with this for hours now, and I don't know what is wrong. I am trying to make a list of registered users in Laravel but it keeps giving me the error:

"Undefined variable: users (View: C:\xampp\htdocs\laraveltest1\links\resources\views\home.blade.php)"

I have asked around on the Laravel Discord server. We've tried several things with no luck such as changing names and changing up the code.

Home.blade.php

@foreach ($users as $user) {
<tbody>
<tr>
    <td>{{ $user->name }}</td>
</tr>
</tbody>
@endforeach

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

}

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->get();

        return view()-> with ('home', ['users' => $users]);
    }
}

I want to have a list, but it gives me an error code stated above.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
  • 2
    You don't appear to have any debugging in there. Does `$users` get set in the controller? Do you have issue connecting to your database? Do you definitely have a table in the DB called `users`? – Obsidian Age Jan 28 '19 at 21:54
  • What do you mean by setting in the controller? And database is fine. I can login with it. Users table is also in the database @ObsidianAge – Javaprogrammern00b Jan 28 '19 at 21:55
  • That's not how you use `with`. `return view('home')->with('users', $users)`. – ceejayoz Jan 28 '19 at 21:58

2 Answers2

3

Try this:

use App\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();

        return view('home', compact('users'));
    }

} 

And in your view

@foreach($users as $user)
{{$user->name}}
@endforeach
Piazzi
  • 2,490
  • 3
  • 11
  • 25
0

Adding to @LucasPiazzi's answer.

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->get();

        return view('home')->with(['users' => $users]); //take a closer look here
    }
}

This is how you pass a variable to a view from controller. now if you add a {{ dd($users) }} to the home.blade.php you should be able to see a dump of the the $users variable

Shobi
  • 10,374
  • 6
  • 46
  • 82