Skip to content
Advertisement

Laravel AJAX: insert with loop (looping DB table row)

I’m new in Laravel and Ajax, and I have working code (see below).

I have 2 tables, criteria and rating.

I want to query first the table named:criteria like (select * from criteria where level = 1), then using the result, I want to save multiple rows in “ratings” using some field of query result + some input variable from user.

Like this:

for (i = 0; i < criteria-result.length; i++) {
   $addItem= New Rating;
   $addItem->empname = $request->empname; //this is from user this is a repeating value
   $addItem->criteria = criteria-result[i].(criteria)
}

Existing Ajax:

$.ajax({
type: 'POST',
url: 'generate-rating-criteria',
data: {
'employee_name':  $("#emp_name").text(),
},
success: function()
{
    swal("Saved", "Ok", "success")
},
error: function(xhr, status, error)
{

    var err = eval("(" + xhr.responseText + ")");
     alert(err.Message);
}
});

Existing Controller:

 $addItem= New Rating;
 $addItem->employee_name =  $request->employee_name;
 $addItem->save();

Advertisement

Answer

You can just use a count() method instead of length.

$criteria = DB::table('criteria')->where('level', 1)->get();

for ($i = 0; $i < count($criteria); $i++) {
    $addItem= New Rating;
    $addItem->empname = $request->empname;
    $addItem->criteria = $criteria[$i]->criteria; /* if criteria column exist in the rating table. */
    $addItem->save();
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement