JsWizard
JsWizard

Reputation: 1749

Get the value instead of key with Laravel collection

$job_types = DB::table('jobs')->pluck('job_type')->unique();

Upper code return a collection as below.

enter image description here

Also below Laravel Blade code make select list with upper collection.

<!-- Job Type Field -->
<div class="form-group col-sm-4" >
    {!! Form::label('job_type', 'Emne:') !!}        
    {!! Form::select('job_type', $job_types, null, ['class' => 'form-control', 'id' => 'job_type']) !!}
</div>

This is return view as select box. enter image description here

So my goal was post selected value in the select box. but I got these keys like 0, 2, 17, 6 as value in the DB. I got still only KEY instead of Value.

How could I get the value to insert data into DB?

Upvotes: 1

Views: 2623

Answers (3)

vietanhyt
vietanhyt

Reputation: 668

See: https://laravel.com/docs/4.2/html#drop-down-lists

Form::select('size', array('L' => 'Large', 'S' => 'Small'));

Array keys will be taken as value of select.

So, your problem is your $job_types array is not formatted right with your request.

If you want to get job_type as select value, make sure that they are $job_types key.

Change:

$job_types = DB::table('jobs')->pluck('job_type')->unique();

to

$job_types = DB::table('jobs')->pluck('job_type', 'job_type')->unique();

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

Use groupBy():

$job_types = DB::table('jobs')->groupBy('job_type')->pluck('job_type');

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You can simply give the second parameter to the pluck method:

$job_types = DB::table('jobs')->pluck('job_type', 'job_type')->unique();

However, I think you should reconsider the practice of storing the value as it may result in database normalization violations.

Upvotes: 0

Related Questions