Reputation: 59
Good evening, I'm trying to make a log-in page that displays a redirection button when there are not registers in the users database. When there are one or more registers in the database, display all the users to select one of them. The problem is that the view doesn't change when the database has a register.
Here you have the blade template code:
@if(empty($users))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Create user</button>
</div>
</div>
@else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
@endif
Here you have the controller code:
public function index()
{
$users = User::all();
return view('users.index')->with('users', $users);
}
Here you have the web.php routing:
Route::get('/', function () {
return view('landing');
});
Route::get('/newUser', function () {
return view('createUser');
});
Route::resource('users', UserController::class);
Can anyone help me? I don't know to solve this...
Upvotes: 0
Views: 71
Reputation: 59
It's solved, the problem was the routing with the blade's file name. I putted it in a login folder and changed the route in web.php
Anyways thanks to everybody for losing a little bit of your time trying to h
Upvotes: 0
Reputation: 29258
empty($users)
is not compatible with the result of $users = User::all()
. ::all()
returns a Collection
, which is an Object
:
Illuminate\Database\Eloquent\Collection {#3357
all: [],
}
Using empty($users)
on this Object
will return false
. You can use a number of Collection
methods, or the PHP method count()
to determine this:
@if($users->count() == 0)
# OR
@if(!$users->count())
# OR
@if(count($users) == 0)
# OR
@if(!count($users))
# OR
@if($users->isEmpty())
# Etc etc...
I'd recommend to use ->isEmpty()
for clarity, but I provided all of them to show different approaches.
There's a ton of useful methods available here:
https://laravel.com/docs/8.x/collections#available-methods
Edit: If the same view is being rendered more than once, $users
needs to be available, or checked via isset()
:
@if (!isset($users) || $users->isEmpty())
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Create user</button>
</div>
</div>
@else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
@endif
Upvotes: 1