12

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.

1
  • Can you please update your question with the html markup ? Commented Jul 10, 2016 at 5:43

3 Answers 3

41

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help, one more query, can you please assist me doing reverse of this, now while editing I want to fetch the string from table and show it as multiselect.
To convert a string into array, you can use explode(',', $string);
2

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);
}

Comments

0

If you are using a multiselect, that probably means that you need a many to many relationship and a pivot table. Kind of like how posts can belong to many tags and tags can belong to many posts.

In your case this would probably be between news and the news_types tables.

1 Comment

thanks for your answer but I want to store this as a string in single table instead of maintaining multiple tables and their relationship.... I know my approach doesn't fit when it comes to Normalization of Database....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.