kavi
kavi

Reputation: 149

how to save checkbox value in array form?

How to save multiple checkbox value into database? now the value is storing in different rows. example: i selected value 1 and 2.so the value 1 in 1 row and value 2 in another row.

blade

  <form enctype="multipart/form-data" action="/report/{{$postqs->id}}" 
     method="POST"> 

   <input type="checkbox" name="item[]" value="one" />1
   <input type="checkbox" name="item[]" value="two" />2
   <input type="checkbox" name="item[]" value="three" />3


 <div class="row">
<div class="form-group">
<label class="control-label col-sm-2"> Others:</label>
<div class="col-sm-7">
 <textarea name="report" id="report" class="form-control"></textarea>
 </div>
 </div>
 <input type="hidden" name="_token" value="{{ csrf_token() }}">
 <input type="submit" class="pull-right btn btn-sm btn-primary">
 </div></div></div>

</form>

Report model

protected $fillable = ['report','postqs_id','user_id','item'];

Store controller :

   public function store(Request $request,Postqs $postqs,$id,Report $report, 
   Admin_report $admin_report)
{

    foreach ($request->input("item") as $key=>$value){
        $add_item = new Report;
         $add_item->item= $value;
         $add_item->user_id= Auth::user()->id;
         $add_item->postqs_id=$id;
         $add_item->save();

        return back();

    }

Upvotes: 1

Views: 1317

Answers (2)

Salar Bahador
Salar Bahador

Reputation: 1494

You should separate items as key and value so that you can save the value and the error it gives you shows that it needs user_id, so add the user_id to it., and your code should look like this:

foreach ($request->input("item") as $key=>$value){
       $add_item = new Report;
        $add_item->item= $value;
        $add_item->user_id= Auth::user()->id;
        $add_item->postqs_id=$id;
        $add_item->save();
}

Because you want the value of the checkboxes, not the key. In the way you do it, it saves key and value together in the item column.

#Update

In this situation (saving array into DB) you don't put item input into foreach loop, and just save it as what it is, before that you must tell to your model to treat that as an array by putting $casts property into Report model:

protected $casts = [
        'items'=>'array',
    ];

This way it should save as array into items column. after that you just save items like this code below:

        $add_item = new Report;
        $add_item->item= $request->input("item");
        $add_item->user_id= Auth::user()->id;
        $add_item->postqs_id=$id;
        $add_item->save();

Note that there is no need for foreach loop in this scenario.

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

It seems you need to add user_id to insert a new Report.

$user = auth()->user();


foreach ($request->input("item") as $item){
    $add_item = new Report;
    $add_item->user_id= $user->id;
    $add_item->item= $item;
    $add_item->save();
}

Upvotes: 0

Related Questions