MalcolmInTheCenter
MalcolmInTheCenter

Reputation: 1605

Why is my variable displaying incorrect value in Laravel 5.4 Blade file?

I have a variable $country_code that is displaying the correct value in one part of my form but not in a different part. Why is this happening?

This is my code:

{{ Form::open(['action' => ['PinVerificationController@valid'],'id'=>'pin_code_form']) }}
    //$country_code shows 1
    We sent a text message to {{$country_code}} {{$phone_number}}. You should receive it within a few seconds.<br><br>
    {{ Form::label('Pin Code', null, ['class' => 'control-label']) }}
    {{ Form::hidden('country_code', $country_code) }}//<------shows 1-US instead of 1
    {{ Form::hidden('phone_number', $phone_number) }}
    {{ Form::hidden('type', $pin_notification_type) }}
    {{ Form::text('pin_code', null,['placeholder' => 'Pin Code'])}}<br><br>
    Enter a 4 digit pin you received by phone.
    <br>
    <br>
    {{ Form::submit('Verify',['name'=>'validate'])}}

{{ Form::close() }}

So if I set $country_code to "1" in my controller it'll display We sent a text message to 1 5555555. You should receive it within a few seconds. But if I do an inspect element on my hidden form it displays 1-US. I've tried php artisan view:clear and php artisan clear-compiled but the problem still persists.

I've also tried hardcoding a value {{ Form::hidden('country_code', 'asdf') }} and i'm not seeing the change. I tried adding a test {{ Form::hidden('country_code1', 'asdf') }} and see the update.

I also renamed country_code to country_code111 for my hidden field and it displayed the correct value of 1. I thought it was a caching issue but like I mentioned I've tried php artisan cache:clear and the problem is still there.

Upvotes: 3

Views: 1297

Answers (1)

Brad
Brad

Reputation: 10660

Since you are using Laravel 5.4, I assume you are using Form from the LaravelCollective, since they were removed from baseline Laravel in 5.x.

LaravelCollective Forms will override the value you provide to the input if it exists in the request data, or in old posted data (the old() function). I suspect this is the case for you.

You can see this behavior implementation here.

To solve this problem, you have a few options:

  1. change the name of the request parameter feeding into the page (if you have control over it)
  2. rename your field name to something that doesn't conflict
  3. Don't use Form:: to generate the form and just use classic html/Blade to create the hidden input automatically

Personally, I would recommend #3 because then you have full control over your code.

<input type="hidden" name="country_code" value="{{ $country_code }}"/>

Upvotes: 6

Related Questions