Maysh
Maysh

Reputation: 41

Cannot save multi-select dropdown value to the database

I want to save multi-select dropdown value to the database.

Here is blade.php

 <select name="namedropdown[]" id="namedropdown" class="selectpicker" multiple data-live-search="true">
    <option value="" disabled selected>Nothing selected</option>
        @foreach ($tdropdown as $tdrop)
        <option value="{{$tdrop}}">{{$tdrop}}</option>
        @endforeach
 </select>

enter image description here

Here is save function in controller

public function empstore(Request $request){

$employee = new employee();

$employee->namedropdown = $request->input('namedropdown');
$employee->namedropdown = implode(',', $employee->namedropdown);

$employee->save();
return redirect()->route('employee.index')->with('success','Data Added');

}

From my code it comes error as Array to string conversion

Please help me to save multi-select dropdown value to the database. Thank you in advance.

Upvotes: 0

Views: 909

Answers (3)

sinemunll
sinemunll

Reputation: 1

You should do it this way

   $employee->namedropdown = implode(',', $request->input('namedropdown'));

Upvotes: 0

Ahmad Ra&#39;fat
Ahmad Ra&#39;fat

Reputation: 21

This line here looks wrong

$employee->namedropdown = $request->input('namedropdown');

the $request->input('namedropdown') will return an array and you try to assign it is returned value to $employee->namedropdown which I believe it is string.

So you can better do it this way directly:

$employee->namedropdown = implode(',', $request->input('namedropdown'));

Hope this helps!

Upvotes: 2

zlodes
zlodes

Reputation: 784

You don't need to assign the $request->input('namedropdown') into the model.

Try this code:

public function empstore(Request $request){

$employee = new employee();
$employee->namedropdown = implode(',', $request->input('namedropdown'));

$employee->save();

return redirect()->route('employee.index')
    ->with('success','Data Added');
}

P.S.: You should improve your code style according the PSR1, PSR2 and PSR12. Methods must be camel-cased, class-names must be upper-camel-cased.

Upvotes: 2

Related Questions