Meysam Saberi Meysam Saberi - 7 months ago 106
PHP Question

checkbox to mysql in laravel 5.2

how to save checkbox value to database ?

my view code:

<input type="checkbox" name="checkbox" id={{$cat->id}} value={{$cat->id}}>


my controller code:

public function submitArticle(){
$article = new Post();
$article->title= Input::get('title');
$article->body= Input::get('body');
$article->cat = Input::get('checkbox');
$article->save();
$articleId = $article->id;
return $articleId;
}

Answer

use this code

<input type="checkbox" name="checkbox[]" id={{$cat->id}} value={{$cat->id}}>

and in controller

if(is_array($checkbox)){
        $relationCategory = $checkbox;
        foreach ($relationCategory as $relCat){
            $rel = new Relationship();
            $rel->post_id = $articleId;
            $rel->cat_id = $relCat;
            $rel->save();
        }
    }
Comments