📜  laravel model where update - PHP (1)

📅  最后修改于: 2023-12-03 15:02:35.366000             🧑  作者: Mango

Laravel Model Where Update

Laravel is a popular PHP framework that provides convenient and easy to use functions to work with databases. One of the main features of Laravel is its built-in ORM (Object Relational Mapping) called Eloquent. In this tutorial, we will learn how to use Eloquent to update records in a database table based on a condition using Laravel's where() method.

Prerequisites

Before proceeding with this tutorial, you should have:

  • A basic understanding of Laravel
  • A Laravel project set up on your local machine
  • A database connection set up in your Laravel project
Model Where Update

To update records in a database table based on a condition using Eloquent, we can use the where() method followed by the update() method. Here is an example:

$affectedRows = User::where('status', 1)
                ->update(['points' => 100]);

In this example, we are updating the points field of all users whose status field is 1. The update() method returns the number of affected rows, which we store in the $affectedRows variable.

Updating Multiple Fields

We can also update multiple fields at once using the update() method. Here is an example:

$affectedRows = User::where('status', 1)
                ->update([
                    'points' => 100,
                    'level' => 2,
                ]);

In this example, we are updating the points and level fields of all users whose status field is 1.

Conclusion

In this tutorial, we have learned how to use Laravel's Eloquent to update records in a database table based on a condition using the where() method. This is a powerful feature of Laravel that makes it easy to work with databases in an object-oriented way.