skip to Main Content

Please help me, I’m new to Laravel. I’m trying to view data from my table but it shows this error. I already tried different methods but all without success and I use Laravel 9.

And sorry if this problem got anwsered a lot in the past, I didnt find any solution that worked for me im sitting on this problem now for 2 days (I feel kinda stupid).

All error messages.

Undefined variable $users

Row: 11 in usercrud.blade.php

@foreach ($users as $user)

resourcesviewsincludesusersusercrud.blade.php: 11  

resourcesviewsincludesusersusercrud.blade
.php: 11 require

IlluminateFoundationBootstrapHandleExceptions: 11
handleError

resourcesviewsadmindashboard.blade.php:8 require

app -> http -> controller -> UserController

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;

class UserController extends Controller
{
    public function index()
    {
        $users = User::orderBy('id')->paginate(10); 
        return view('includes.users.usercrud', compact('users'));
    }

    public function create()
    {
        return view('includes.users.create');
    }

    public function store(Request $request)
    {
    
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required',
           
        ]);

       
        User::create($request->all());

        return redirect()->route('includes.users.usercrud')
            ->with('success', 'User created successfully.');
    }

    public function edit(User $user)
    {
        return view('includes.users.edit', compact('user'));
    }

    public function update(Request $request, User $user)
    {
        
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $user->id,
           
        ]);

        
        $user->update($request->all());

        return redirect()->route('includes.users.usercrud')
            ->with('success', 'User updated successfully.');
    }

    public function destroy(User $user)
    {
       
        $user->delete();

        return redirect()->route('includes.users.usercrud')
            ->with('success', 'User deleted successfully.');
    }
}

views -> includes -> users -> usercrud.blade.php

<h1>User List</h1>
<a href="{{ route('includes.users.create') }}">Create New User</a>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Role</th>
        <th>Actions</th>
    </tr>
    @foreach ($users as $user)
        <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
            <td>{{ $user->role }}</td>
            <td>
                <a href="{{ route('includes.users.edit', $user->id) }}">Edit</a>
                <form method="POST" action="{{ route('includes.users.destroy', $user->id) }}">
                    @csrf
                    @method('DELETE')
                    <button type="submit">Delete</button>
                </form>
            </td>
        </tr>
    @endforeach
</table>

{{ $users->links() }}

views -> admin -> dashboard.blade.php

@extends('layouts.app')

@section('content')
    <div class="container mt-4 text-light">
        <h2>Welcome to the Admin Dashboard!</h2>
    </div>
    <div>
        @include('includes.users.usercrud')
    </div>
@endsection

routes -> web

use AppHttpControllersAuthController;
use AppHttpControllersAdminController;
use AppHttpControllersUserController;
use AppHttpMiddlewareAdminMiddleware;

Route::group(['middleware' => ['admin']], function () {
    Route::get('admin/dashboard', [AdminController::class, 'adminDashboard'])->name('admin.dashboard');
    Route::get('/users', [UserController::class, 'index'])->name('includes.users.usercrud');
    Route::get('/users/create', [UserController::class, 'create'])->name('includes.users.create');
    Route::post('/users/store', [UserController::class, 'store'])->name('includes.users.store');
    Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('includes.users.edit');
    Route::put('/users/{user}', [UserController::class, 'update'])->name('includes.users.update');
    Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('includes.users.destroy');
});

I tried a lot of other methods from stackoverflow already but for some reason it wont work for me.
Also looked now at global variables but that also dont work.

2

Answers


  1. your code seems correct but I think there’s a minor inconsistency in your naming convention. could you please try this, I’ve changed the route names to use admin.users instead of includes.users like this

    Route::group(['middleware' => ['admin']], function () {
        Route::get('admin/dashboard', [AdminController::class, 'adminDashboard'])->name('admin.dashboard');
        Route::get('/users', [UserController::class, 'index'])->name('admin.users.index');
        Route::get('/users/create', [UserController::class, 'create'])->name('admin.users.create');
        Route::post('/users/store', [UserController::class, 'store'])->name('admin.users.store');
        Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('admin.users.edit');
        Route::put('/users/{user}', [UserController::class, 'update'])->name('admin.users.update');
        Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('admin.users.destroy');
    });
    

    Let me know if you find another bug after this change.

    Login or Signup to reply.
  2. The issue is that you are including the users crud into the dashboard, but the adminDashboard controller does not pass a list of users for use when it renders the dashboard section.

    Make sure wherever you want to display a list of users that you pass this list from the controller

    It is not sufficient to pass the list of users from the UserController because you never access this controller when you show the dashboard from the adminDashboard controller.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search