📜  laravel where - PHP (1)

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

Laravel Where - PHP

What is Laravel Where?

Laravel Where is a method used in Laravel Framework for PHP that allows developers to filter records from the database based on certain conditions.

How to use Laravel Where

Laravel Where method can be used in two ways:

  1. Using the where method on a query builder instance:

    $users = DB::table('users')
                ->where('name', 'John')
                ->get();
    

    This will return all records from the "users" table where the "name" column is equal to "John".

  2. Using the where method on an Eloquent model instance:

    $users = User::where('name', 'John')->get();
    

    This will return all records from the "users" table where the "name" column is equal to "John".

Laravel Where Examples
Basic Where

To get all records from the "users" table where the "name" column is equal to "John", we can use the following code:

$users = DB::table('users')
            ->where('name', 'John')
            ->get();
Where with Multiple Conditions

To get all records from the "users" table where the "name" column is equal to "John" and the "age" column is greater than or equal to 18, we can use the following code:

$users = DB::table('users')
            ->where('name', 'John')
            ->where('age', '>=', 18)
            ->get();
Or Where

To get all records from the "users" table where the "name" column is equal to "John" or the "name" column is equal to "Jane", we can use the following code:

$users = DB::table('users')
            ->where('name', 'John')
            ->orWhere('name', 'Jane')
            ->get();
Where In

To get all records from the "users" table where the "name" column is either "John", "Jane", or "Mary", we can use the following code:

$users = DB::table('users')
            ->whereIn('name', ['John', 'Jane', 'Mary'])
            ->get();
Conclusion

Laravel Where method is an essential tool for filtering records from the database based on certain conditions. It provides a flexible and easy-to-use way to retrieve data from the database.