laravel - Undefined variable: users (View: /home/swit/public_html/manager/resources/views/users.blade.php)
Get the solution ↓↓↓i keep getting this error and i don't know what's wrong. The code seems correct so please help me if you can figure out what's giving me this error. "Undefined variable: users (View: /home/swit/public_html/manager/resources/views/users.blade.php) " thanks
this is my blade.php
<tbody>
@foreach ($users as $key)
<tr>
<td>{{$key->name}}</td>
<td>{{$key->email}}</td>
<td>{{$key->phone}}</td>
<td>{{$key->created_at}}</td>
</tr>
@endforeach
</tbody>
and this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function user(){
$users = DB::table('users')->get();
return view('users', compact('users'));
}
}
and this is my route
Route::get('/users', function () {
return view('users');
})->middleware(['auth'])->name('users');
Answer
Solution:
change your route function definition for the controller
Route::get('/users', [\App\Http\Controllers\UserController::class,'user'])->middleware(['auth'])->name('users');
Answer
Solution:
The error is in your route file, You should create a route which use controller and not an function as you have define,
When you define a route using closure, that function will be executed on each request that match that route.
You should define a route to that controller like this
// At the top of the web.php file
use App\Http\Controllers\UserController;
// Here you define the route
Route::get('/users', [UserController::class, 'user']])
->middleware(['auth'])->name('users');
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your lock file does not contain a compatible set of packages. please run composer update.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.