phplaravellaravelcollective

How to set default value in laravel collective form


i'm fetching data from database and want to make dropdown list with one value selected by default

i tried this Laravel-5 how to populate select box from database with id value and name value

but nothing happen

my view file:

<div class="row">
    <!-- Country ID Field -->
    <div class="form-group col-sm-6">
        {!! Form::label('country_id', 'Country ID:') !!}
        {!! Form::select('country_id',$countries, isset($user) ? $user->country_id : 'Nepal', ['class' => 'form-control']) !!}
    </div>

i'm new to laravel-collective..please help :)


Solution

  • The Laravel Collective code is really helpful... but it is also buggy in some odd ways.

    There is an automatic binding that you can take advantage of by using null in the Collective select() constructor:

    <div class="row">
        <div class="form-group col-sm-6">
            {!! Form::label('country_id', 'Country ID:') !!}
            {!! Form::select('country_id',$countries, null, ['class' => 'form-control']) !!}
    </div>
    

    This is usually really good if you use form-model binding on the forms. However, there may be cases when it doesn't pick up the user model. If so, you were correct with your original code. BUT, for some reason, Collective occasionally reads the isset section better when the isset block is within parenthesis:

    <div class="row">
        <div class="form-group col-sm-6">
            {!! Form::label('country_id', 'Country ID:') !!}
            {!! Form::select('country_id',$countries, (isset($user) ? $user->country_id : 'Nepal'), ['class' => 'form-control']) !!}
    </div>
    

    Try either of these - hopefully one will help you.

    The other potential item to check is to make sure your $countries are set and contain some ids, INCLUDING the id for the $user->country_id. If the user's country is not in the $countries list, it will not work even if the user's id is set.