Roberto Remondini
Roberto Remondini

Reputation: 272

How to load data into Select2 with Laravel

i'm trying to load into Select2 the selected value extracted from the DB. Id values are saved in a JSON field which cointains the id values or the field '*' that I manage as 'All'.

This is my controller method:

$data['field_id'] = array();
$field_id_array = json_decode(User::find($id) -> field_id);
if( $field_id_array !== null ) {
    $field_array = Campo::whereIn('id',$field_id_array)->pluck('field_name','id');
    if( in_array( '*' , $field_id_array ) ) {
        $field_array -> prepend( 'All' , '*' );
    }
    $data['field_id'] = $field_array;
}    
return view('create', $data);

This is my View, I'm using Blade:

<select id="field_id" name="field_id[]" multiple>
    @if(!empty($field_id))
        @foreach($field_id as $f)
            <option value = "{!! $f->id !!}" selected >{!! $f->field_name !!}
            </option>
        @endforeach
    @endif
</select>

The error showed is:

Trying to get property of non-object

If I use only {!! $c !!} inside the loop of the view I haven't mistake but it show only the field field_name.

I'm using Select2 with ajax search, but I haven't post the code because I think the error is 99.9% in the controller's method.

Anyone have idea for resolve the problem?

Upvotes: 4

Views: 8619

Answers (2)

Leandro Epifani
Leandro Epifani

Reputation: 1

If you are using blade and you use pluck to create the array with only 2 types. You can use this syntax passing $field_array to the view:

{{Form::select('field_id[]',
                $field_array,
                '', array('class'=>'your-class',
                          'id' => 'field_id',
                          'multiple'))}}

Upvotes: 0

YouneL
YouneL

Reputation: 8361

Collection::pluck method return an associative array in your case not an array of objects, that's why your loop should look like this:

@foreach($field_id as $id => $field_name)
    <option value = "{{ $id }}" selected >{{ $field_name }}</option>
@endforeach

Upvotes: 3

Related Questions