Search code examples
laravellaravel-7

insert into 2 tables (pivot) array values from multiple select dropdown list


I work with events and years, one event can be in several years and a year can have several events (pivot table created between the two tables).

I change my single dropdown list in multiple list :

<select id="year_id" type="text" class="form-control selectpicker @error('year_id') is-invalid @enderror" name="year_id[]" required multiple>
<option disabled>--Choisir--</option>
        @foreach($years as $year)
                @if(old('year') == $year->id)
                     <option value="{{ $year->id }}" selected>{{ $year->name }}</option>
                @else
                     <option value="{{ $year->id }}">{{ $year->name }}</option>
                @endif
        @endforeach

</select>

The goal is to select several years for one same event.

I don't know why, but I think I'm not able to validate the form.

This is my controller code :

public function store(Request $request)
    {

        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'mnemonique' => 'required|string|max:255',
            'color' => 'required|string|max:255',
            'year_id[]' => 'required|array',
            'year_id[].*' => 'required|integer|exists:years,id'
        ]);

        $evenement = new Evenement();
        
         //dd($validatedData);
        // $evenement->create($validatedData);

        

        $evenement = Evenement::create($validatedData);
        $evenement->years()->sync([$validatedData['year_id[]']]);

I'm not able to insert the events into the pivot table and the new event into the event table.

If I use dd(), I still have a refresh of the form, I think I don't go into the controller...

Do you see something please ?

Thank you in advance.


Solution

  • Change validation rule to

    'year_id' => 'required|array',
    'year_id.*' => 'required|integer|exists:years,id'
    

    To show Error message in view

    @error('year_id')<div class="invalid-feedback">{{$message}}</div> @enderror
    

    and

     @if($errors->has('year_id.*')) <div class="invalid-feedback">Selected Year doesnt exists</div>  @endif
    

    While saving into database

     $evenement->years()->sync($validatedData['year_id']);