I have a Project
model which has a multi-select field called project_type
. I am using Select2 for the field.
I've set up an enum in config/enum.php
like this:
<?php
return [
'project_types' => [
'0' => 'WordPress Brochure Website',
'1' => 'WordPress WooCommerce Website',
'2' => 'Drupal Website',
'3' => 'SEO',
'4' => 'Branding',
'5' => 'Bespoke Web App'
]
];
?>
In my create
view I have a form with the field as such:
{{ Form::open(array('url' => 'projects')) }}
<div class="form-group">
{!! Form::label('Project Type') !!}
{!! Form::select('project_type[]', Config::get('enums.project_types'), null, ['multiple'=>'multiple']); !!}
</div>
{{ Form::submit('Create Project', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
Then in my controller when I save the multi-select field values I convert the array into a string to store into the DB:
public function store(ProjectRequest $request)
{
$project_type = $request->input('project_type');
$project_type = implode(',', $project_type);
$input = $request->except('project_type');
$input['project_type'] = $project_type;
Project::create($input);
return redirect()->route('projects')->with('message', 'Rate created.');
}
This will store the multi-select field in a format like this 0,1,3
.
This saves fine however now when I want to edit the project I need to pull out the values from the db and populate the multi-select field, this is where I'm struggling, here is what I have in my edit
view.
{{ Form::model($project, array('route' => array('projects.update', $project->id), 'method' => 'PUT')) }}
<div class="form-group">
{!! Form::label('Project Type') !!}
{!! Form::select('project_type[]', Config::get('enums.project_types'), 1, ['multiple'=>'multiple']); !!}
</div>
{{ Form::submit('Update Project', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
At the moment you can see I've hard coded the default value for the multi-select field to 1
but is there a way I can set the default value of the multi-select field to what is stored in the db?