DEV Community

Laravel Indonesia
Laravel Indonesia

Posted on

Laravel 9 Multi Update or Insert with this 'Magic'

Image description
Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.

If you would like to perform multiple "upserts" in a single query, then you should use the upsert method instead. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:

if(count($data) > 0) {
   $error = '';
}
PostNilai::upsert($data,['id','user_id','nilai_id','score_s1','score_s2','score_s3','score_s4','score_s5']);
return redirect(route('nilai'))->with('error', $error);

Enter fullscreen mode Exit fullscreen mode

watch full tutorial
https://youtu.be/eMBS80A2SzI

Top comments (0)