Rowel Abenio
Rowel Abenio

Reputation: 53

Laravel Conditional Clause When()

I am new to Laravel and have encountered a problem using when() function. To start this I do have a form consisting of 3 input fields named: name, email, and password.

<form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>

Also I have this code inside a controller file.

$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

$role = $request->input('name');

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.

Upvotes: 2

Views: 772

Answers (3)

UfguFugullu
UfguFugullu

Reputation: 2147

If the $role variable is set then the mysql query will look like this

select * from `users` where `role_id` = 1

If $role isn't set like false then the mysql query will look like this

select * from `users`

You should edit your query for example with if and use different where()

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

When $role is false, the closure is not executed, so you'll simply get this query:

User::get();

This query will just return all users.

You need to use simple where() in this situation:

User::where('username', $role)->first();

It will return an User object or null if $role is empty.

Upvotes: 0

Vishal Varshney
Vishal Varshney

Reputation: 905

The when method will execute the given callback when the first argument given to the method evaluates to true.

Upvotes: 2

Related Questions