Multiple SelectBox Usage in Laravel
25-02-2020We can use following codes for multiple select in Laravel:
Blade Template:
<div class="form-group col-sm-6"> {!! Form::label('project_contents', 'Project Contents:') !!} <i>(You can choose multiple items)</i> @if(!isset($project)) {{Form::select('project_contents',$project_contents,null, array('data-placeholder'=>'Seçiniz','class' => 'form-control select','multiple'=>'multiple', 'name'=>'project_contents[]','required'=>''))}} @endif @if(isset($project)) <select multiple="multiple" name="project_contents[]" id=project_contents" class="form-control select" required="required"> @foreach($project_contents as $aKey => $content) <option value="{{$aKey}}" @if(in_array($aKey,$project->project_contents)) selected="selected"@endif> {{$content}} </option> @endforeach </select> @endif <div class="help-block with-errors"></div> </div>
Controller:
public function store(HttpRequest $request) { $input=$request->all(); $input['project_contents'] = json_encode($input['project_contents']); } public function edit($id) { $project = $this->projectRepository->find($id); return view('projects.edit')->with('project', $project) ->with("project_contents", $this->getProjectContents()); } private function getProjectContents() { $projectContents = ProjectContent::pluck('name', 'id'); $projectContents = $projectContents->toArray(); return $projectContents; }
Project model
class Product extends Model { public $table = 'products'; public $fillable = [ 'project_contents' ]; protected $casts = [ 'project_contents' => 'array', ]; }