GiacomoM's avatar

Blade: check if old values are empty or not

Hi, as the subject, I need to know if the old values are empty or not, in blade. I mean, I need to know if we are coming back from a post or we are in the first page request.

How can I do it?

Thanks.

0 likes
6 replies
Thijmen's avatar

You can do:

if(old('value', null) != null)
1 like
AucT's avatar
old('_token') === null

true - first request false - old request (after submit)

3 likes
walidabou's avatar
value="{{old('input') ? old('input') : ''}}"
1 like
madman81's avatar

I ran into this same issue. In my case it was an array/multi select, for instance for user roles. If an admin wants to remove all roles but the form has another error, the form should be returned with an empty list of roles, instead of the old roles. Something like old('roles', $user->roles) does not work because old() just checks if the key exists in the session.

I solved it with the suggestion of @walidabou:

@php
    $old_roles = (old('_token') !== null) ? collect(old('roles')) : $user->roles;
@endphp
@foreach($roles as $role)
    <div class="form-check">
        <input type="checkbox" name="roles[]" value="{{ $role->id }}" @if($old_roles->contains($role->id)) checked @endif>
        <label>{{ $role->display_name }}</label>
    </div>
@endforeach
JoshP's avatar

I ran into this issue on a dropdown, where a certain value is selected by default, but if validation fails, I want the selected value to remain.

<option value="5" {{ old('difficulty', null) === null ? 'selected' : ''}} {{ old('difficulty') === '5' ? 'selected' : '' }}>
	5 - Average
</option>

Please or to participate in this conversation.