Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store multi select values in Laravel 5.2

I have a form which stores News.

enter image description here

Here I am using Multiselect and I want to save all the selected option in the table as say Users,staff,cinemahall as a string.

My controller function to store values is

 public function store(Request $request)
{

    $input=$request->all();

    General_news::create($input);
    return redirect()->back();
}

This function store the all submitted fields but for multiselect it stores only last option i.e cinemahall

enter image description here

When form is submitted all selected options are displayed but it's not saving in database table properly.

help me to solve this issue.

like image 505
dollar Avatar asked Jul 10 '16 05:07

dollar


2 Answers

Make sure you set the name attribute to an array

<select multiple="multiple" name="news[]" id="news">

To store it as string separated by commas

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

You have a string which will look like Users,staff,cinemahall. Now, instead to retrieve all input, you may need to retrieve it one by one, since you need to mutate the news value. Additionally, you can also use except() method to exclude news from mass getting all value.

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

$input = $request->except('news');
//Assign the "mutated" news value to $input
$input['news'] = $news;

General_news::create($input);
return redirect()->back();
like image 171
Chay22 Avatar answered Nov 14 '22 11:11

Chay22


Thanks @Chay22

you could also use Mutators and Accessor https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

public function setFooAttribute($value)
{
    $this->attributes['foo'] = implode(',',$value);
}

public function getFooAttribute($value)
{
    return explode(',',$value);
}
like image 42
Bdwey Avatar answered Nov 14 '22 11:11

Bdwey