Ad
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');
}
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad