Home > Enterprise >  LARAVEL Insert MULTIPLE ROWS in database
LARAVEL Insert MULTIPLE ROWS in database

Time:09-18

I'm trying to insert multiple row data in two DB tables using single click but this code insert only one row at a time. When i try dd($request->all()); i got data in array but insert only one row. What is the problem and how can i fix it?

protected $table = 'biniyojan';

////Modified Controller//////

public function bbcreate(Request $request)
{

    //dd($request->all());
    $biniyojan_details = new BiniyojanDetails();


    $biniyojan = new Biniyojan();
    $biniyojan->details_id = $biniyojan_details->details_id;
    $biniyojan->date =  $request->date;
    $biniyojan->ab =  $request->ab;
    $biniyojan->school =  $request->school;
    $biniyojan->behora =  $request->behora;
    $biniyojan->save();


    $biniyojan_details = new BiniyojanDetails();
    if (!empty($request->school)) {
        for ($i = 0; $i < count((array)$request->school); $i  ) {
        $biniyojan_details['biniyojan_id'] = $biniyojan->id;
        $biniyojan_details['school'] = $request->school[$i];
        $biniyojan_details['source'] = $request->source[$i];
        $biniyojan_details['kriyakalap'] = $request->kriyakalap[$i];
        //$biniyojan_details->debit_credit = $request->debit_credit[$i];
        //$biniyojan_details->debit_credit_type = $request->debit_credit_type[$i];
        $biniyojan_details['cash'] = $request->cash[$i];
        $biniyojan_details->save();
        }
    }
    return redirect()->back()->with('status', 'Inserted');
} 

/////View Blade////////

 <form method="POST" action="{{ route('bbcreate') }}">
    @csrf
    <div >
        <div >
            <input type="date" placeholder="मिति" value="@php echo $today; @endphp" name="date"  id="inputCity" required>
        </div>
        <div >
            <select id="inputState" placeholder="" name="ab"  required>
                <option>2079-080</option>
                <option>2078-079</option>
            </select>
        </div>



        <div >
            <select id="inputState" name="school"  required>
                <option selected disabled>स्रोत पाउने संस्था </option>
                @foreach ($school_array as $sch)
                <option value="{{ $sch -> name }}">{{ $sch -> name}}</option>
                @endforeach
            </select>
        </div>
    </div>
    <div id="form-field">
        <div >
            <div >
                <select id="source" name="source[]"  required>
                    <option selected disabled value="">स्रोत</option>
                    <option>केन्द्र</option>
                    <option>प्रदेश</option>
                    <option>स्थानीय</option>
                    <option>अन्य</option>
                </select>
            </div>
            <div >
                <select id="kriyakalap" name="kriyakalap[]"  required>
                    <option selected disabled>क्रियाकलाप</option>
                    @foreach ($bini as $bi)
                    <option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option>
                    @endforeach

                </select>
                @foreach ($bini as $bi)

                @endforeach
            </div>
            <div >
                <select name="debit_credit[]" id="debit_credit"  >
                    <option selected="selected" disabled>डेबिट / क्रेडिट</option>
                </select>
            </div>
            <div >
                <select name="debit_credit_type[]" id="debit_credit_type"  >
                    <option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option>
                </select>
            </div>

            <div >
                <input type="text" placeholder="रकम" name="cash[]"  id="price" required>
            </div>
            <div >
                <input type="button"  name="add" id="add" value=" ">
            </div>
        </div>
    </div>
    <div  style="justify-content:left ;">
        <div >
            <input type="text" placeholder="ब्यहोरा" name="behora"  id="behora" required>
        </div>

        <div >
            <input type="submit" id="submit" name="submit" value="राख्नुहोस्" >

        </div>

        @if (session('status'))
        <div >
            {{ session('status') }}
            {{-- message --}}
        {!! Toastr::message() !!}
        </div>
        @endif

    </div>
    <div form-row col-x1-3 id="showdata" >
        <p ></p>
        <p id="showdata" ></p>
    </div>
</form>


//////jQuery For Repeat form////////[enter image description here][1]
<!-- form repeat -->

<script type="text/javascript">
        $(document).ready(function() {
        var html = '<span><div id="form-field"> <div > <div > <select id="source" name="source[]"  required> <option selected disabled value="">स्रोत</option> <option>केन्द्र</option> <option>प्रदेश</option> <option>स्थानीय</option> <option>अन्य</option> </select> </div> <div > <select id="kriyakalap" name="kriyakalap[]"  required> <option selected disabled>क्रियाकलाप</option> @foreach ($bini as $bi) <option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option> @endforeach </select> @foreach ($bini as $bi) @endforeach </div> <div > <select name="debit_credit[]" id="debit_credit"  required> <option selected="selected" disabled>डेबिट / क्रेडिट</option> </select> </div> <div > <select name="debit_credit_type[]" id="debit_credit_type"  required> <option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option> </select> </div> <div > <input type="text" placeholder="रकम" name="cash[]"  id="price" required> </div> <div > <input type="button"  name="remove" id="remove" value="-"> </div> </div> </div></span>';
        var max = 5;
        var x = 1;
        $("#add").click(function() {
            if (x <= max) {
                $("#form-field").append(html);
                x  ;
            }
        })
        $("#form-field").on('click', '#remove', function() {
            $(this).closest('span').remove();
            x--;
        });
    });

</script>

<!-- form repeat -->

CodePudding user response:

As @aynber pointed at, you need to move the line $biniyojan_details = new BiniyojanDetails(); inside the loop so it initiate a new object for each iteration.

Another solution would be to insert all the entries in the same time(better performance). For that, we prepare the data to be inserted first

public function bbcreate(Request $request)
{

    //dd($request->all());
    $biniyojan_details = new BiniyojanDetails();


    $biniyojan = new Biniyojan();
    $biniyojan->details_id = $biniyojan_details->details_id;
    $biniyojan->date =  $request->date;
    $biniyojan->ab =  $request->ab;
    $biniyojan->school =  $request->school;
    $biniyojan->behora =  $request->behora;
    $biniyojan->save();


    $biniyojanDetailsToBeInserted = [];
    if (!empty($request->school)) {
        for ($i = 0; $i < count((array)$request->school); $i  ) {
            $biniyojan_details = [];
            $biniyojan_details['biniyojan_id'] = $biniyojan->id;
            $biniyojan_details['school'] = $request->school[$i];
            $biniyojan_details['source'] = $request->source[$i];
            $biniyojan_details['kriyakalap'] = $request->kriyakalap[$i];
            //$biniyojan_details['debit_credit'] = $request->debit_credit[$i];
            //$biniyojan_details['debit_credit_type'] = $request->debit_credit_type[$i];
            $biniyojan_details['cash'] = $request->cash[$i];
            $biniyojanDetailsToBeInserted[] = $biniyojan_details;
        }
    }
    if ($biniyojanDetailsToBeInserted) {
        BiniyojanDetails::insert($biniyojanDetailsToBeInserted);
    }
    return redirect()->back()->with('status', 'Inserted');
} 

CodePudding user response:

Your code create only one row but the noticeable thing is that it create one row but with last data of the array.

Because you are not making object inside the loop it is outside of the loop so the loop runs on the same object and update its properties each time loop runs and save it.

Make object inside the loop so it make new object each time which means it will create new row each time instead of updating the same row.

There is a better way for this if you have same names of your array keys as database table columns.

Biniyojan::insert($request->data);

It works like this.

User::insert([
    ['name' => 'John', 'email' => '[email protected]'],
    ['name' => 'Marina', 'email' => '[email protected]'],
]);
  • Related