How to store multi select values in Laravel 5.2

后端 未结 3 941
无人及你
无人及你 2020-12-29 11:55

I have a form which stores News.

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

相关标签:
3条回答
  • 2020-12-29 12:04

    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.

    0 讨论(0)
  • 2020-12-29 12:06

    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();
    
    0 讨论(0)
  • 2020-12-29 12:20

    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);
    }
    
    0 讨论(0)
提交回复
热议问题