You need to do something like this.
$order = 1;
$records = Model::all();
foreach($records as $row) {
$row->order = $order;
$row->update();
$order++;
}
With the proper search criteria of course.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I've been stumped on this and tried everything I can think of but I can't get Laravel to execute a working mysql query to reorder a ordering column when deleting a row.
The sample code below shows hard coded values, but I'm passing in dynamic queries. I've also tested hard coded and dynamic and both seem to fail for me.
Sample Images Table Schema:
| id | project_id | order |
| ------------- | ------------- | ------------- |
| 2 | 10 | 1 |
| 3 | 10 | 2 |
| 4 | 10 | 3 |
| 5 | 10 | 6 |
| 6 | 10 | 7 |
Sample simplified query (which works in mysql):
SET @number = 3; UPDATE images SET order = (@number := @number + 1) WHERE id >2 AND project_id = 10
This works in tinker but not laravel:
DB::unprepared($sql);
Laravel code that doesn't update the database but throws no errors:
DB::raw($sql);
Other things I've tried which throw errors including saying there's an error in the query:
DB::statement(DB::raw($sql);
DB::statement($sql);
DB::update($sql);
DB::select($sql);
I've also tried splitting it the statements with no luck:
DB::statement("SET @number = 3;");
$sql = 'UPDATE images SET order = (@number := @number + 1) WHERE id >2016 AND project_id = 10';
$update = DB::update($sql);
Any ideas on what I could be doing wrong or is there a better way to accomplish this using Laravel?
Thanks in advance!
In case anyone runs into this issue, I solved it by putting the sql code into a stored procedure and calling the stored procedure through Laravel. This way, you only need one database call and mysql handles updating the rows.
Please or to participate in this conversation.