Ad

How To Store Multi Select Values In Laravel

- 1 answer

I have many to many relationship between categories and movies. When I check multiple values for categories and insert movie the result on home page selects only one category not all. I tried many things but I wasn't able to resolve this. Here is my code.

upload.blade.php:

<div class="form-group">
    {!! Form::label('category_id', 'Category:') !!}
    {!! Form::select('category_id', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>

Controller:

 public function index(Request $request)
{
    $categories = Category::pluck('category_name', 'id')->all();
    return view('movies.upload', compact('categories'));
}

public function upload(MovieUploadRequest $request)
{
    DB::beginTransaction();
    try {
        $movie = Movie::create($request->all());
        $movie->categories()->attach($request->get('category_id'));
        DB::commit();
    } catch (\Exception $e) {
        DB::rollBack();
    }

    return redirect('home');
}
Ad

Answer

To enable multiple selects, you first of need to change the name of the select input from category_id to category_id[]. This enables posting of multiple variables as an array.

The code should then look like:

<div class="form-group">
    {!! Form::label('category_id', 'Category:') !!}
    {!! Form::select('category_id[]', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>

In your controller, you will then need to loop through the posted id's:

public function upload(...){
    foreach( $request->input('category_id') AS $category_id ){
        $movie = Movie::create($request->all());
        $movie->categories()->attach($category_id);
        ...
    }
}

Edit:

The method attach() also accepts an array of ids as an argument. Thereby, you don't need to loop through the input as above, but can simply use:

public function upload(...){
    $movie = Movie::create($request->all());
    $movie->categories()->attach($request->input('category_id'));
    ...
}
Ad
source: stackoverflow.com
Ad