Chamara Abeysekara
Chamara Abeysekara

Reputation: 1322

saving check box values to the database in laravel

I'm new to laravel. I'm saving some checkbox value to the database using loop the loop work but it only saves the last value in the array to the database.

this is my form

<form action="{{url('resortf')}}" method="post" enctype="multipart/form-data">
            <input hidden name="h_id" value="{{ $hotel->id}}">
            @foreach($facility as $facilities)
            <div class="col-md-4">
                <img src="{{$facilities->image}}" width="50px" height="50px;">
                <label>{{$facilities->name}}</label>
                <input type="checkbox" value="{{$facilities->id}}" name="facilities[]">
            </div>
            @endforeach
            <div class="row">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="submit" class="btn btn-success" value="Next">
                <input type="reset" class="btn btn-success" value="Reset">
            </div>

        </form>

form working fine; $facilities and $hotel are passed from the controller.

this is the store function

public function store(Request $request) {
    $resortfacility = new Resortfacility;
    $loop = $request->get('facilities'); 
    
    foreach ($loop as $value){
        $resortfacility->h_id = $request->get('h_id');
        $resortfacility->f_id = $value;
        
        $resortfacility->save();

    }
}

is there any other way to do this that works?

Upvotes: 5

Views: 9551

Answers (2)

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

The other answer is correct but, bulk insertion might be helpful, as creating new object within foreach loop will make query for every record.

     public function store(Request $request) 
     {
             $facilities = $request->get('facilities');
             $data=array();
             foreach($facilities as $facility)
             {
                 $data[] =[
                            'f_id' => $facility,
                            'h_id' => $request->get('h_id'),
                         ];                 
             }
        }

 Resortfacility::insert($data);

Upvotes: 2

Khallister
Khallister

Reputation: 266

Your problem occurs because you create one instance of Resortfacility, and then you fill in its values and save. The problem is, every time you perform changes to this object in a loop, you are updating existing object and that's why there is only one record in your database, the last one from the loop.

Try making new instance of Resortfacility inside the loop like this:

public function store(Request $request) {
    $loop = $request->get('facilities');
    foreach ($loop as $value){
        $resortfacility = new Resortfacility;
        $resortfacility->h_id = $request->get('h_id');
        $resortfacility->f_id = $value;
        $resortfacility->save();
    }
}

Upvotes: 4

Related Questions