I'm trying to save into my database the checkbox I checked into my view. I have a title, a type_article (dropdown), the theme (checkbox) and contents.
I'm doing this in article_list.blade.view :
@foreach ($themes as $theme)
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="themeCheckbox[]" value="{{ $theme->theme_id }}">
<label class="form-check-label">{{ $theme->nom_theme }}</label>
</div>
@endforeach
My AdminController :
public function createArticle(Request $request)
{
$data = $request->validate([ // $data = $this->validate($request
'titreArticle' => 'bail|required|between:5,40',
'typeArticle' => 'bail|required',
'themeCheckbox' => 'required|array|min:1',
'themeCheckbox.*' => 'required|string|distinct|exists:theme,nom_theme',
'contenuArticle' => 'bail|required',
]);
$type_articles = Type_article::findOrFail($data['typeArticle']);
$article = new Article();
$article->type_article()->associate($type_articles);
$themes = Theme::whereIn('nom_theme', $data['themeCheckbox'])->get();
$article->theme()->associate($themes);
$article->titre = $data['titreArticle'];
$article->contenu = $data['contenuArticle'];
$article->date_creation = date('Y-m-d');
$article->save();
$article->theme()->attach($themes);
return view('admin/panel_admin/panel_admin');
}
Everything is good except the checkbox issue. I do show my error inside my view and thats what appear when I submit the 3 checkboxs :
The selected themeCheckbox.0 is invalid.
The selected themeCheckbox.1 is invalid.
The selected themeCheckbox.2 is invalid.
I do have a pivot table (Article and Theme as table and Article_theme the pivot table).
EDIT :
The problem was $themes = Theme::whereIn('nom_theme', $data['themeCheckbox'])->get();, I need to change nom_theme to id_theme.