rose
rose

Reputation: 197

How to store multi select values in Laravel

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

Upvotes: 0

Views: 7394

Answers (3)

Arnaud LiDz
Arnaud LiDz

Reputation: 311

In your view, use a name like :

<select name="yourfiled[]"></select>.

In controller, to store it in database, just write

$movies->categories = json_encode(yourfield);

Done.

Upvotes: 2

Ole Haugset
Ole Haugset

Reputation: 3797

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

Upvotes: 2

Jahid Mahmud
Jahid Mahmud

Reputation: 1136

You can write this. hopefully this will solve your problem

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

Upvotes: 0

Related Questions