search
HomePHP FrameworkLaravelLaravel development: How to use Eloquent ORM for database query?

Laravel is a popular PHP development framework that provides a series of tools and helper functions to speed up the development of web applications. Among them, Eloquent ORM is one of the tools used for database operations in the Laravel framework, allowing Laravel developers to query and operate the database more quickly. In this article, we will delve into how to use Eloquent ORM for database queries.

  1. Install Eloquent ORM

First, we need to install Eloquent ORM in the Laravel application. We can install Eloquent ORM through Composer, open the terminal, enter the folder where the Laravel project is located, and enter the following command:

composer require illuminate/database

After the installation is complete, we need to set the database connection in config/database.php, as follows As shown:

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

We also need to set the relevant information of the database connection in the .env file, as shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
  1. Define the model

Use To perform database query with Eloquent ORM, we need to define the model first. Model refers to the php class that represents the database table. In Laravel, we can generate the model through the artisan command as follows:

php artisan make:model User

This will create a model named User, which will be mapped to the users table in the database by default. If you want to map to another table, specify the table name in the model using the $table attribute.

class User extends Model
{
    protected $table = 'my_users';
}
  1. Query data

Once the model is defined, we can use Eloquent ORM to query the database. The following are some commonly used query operations:

(1) Query all records

$users = User::all();

(2) Query a single record based on ID

$user = User::find(1);

(3) Query based on other conditions Result set

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

We can add a series of constraints in the where method, such as equal to, not equal to, greater than, less than, in, etc.

$users = User::where('name', '=', 'John')->get();
$users = User::where('age', '>', 18)->get();
$users = User::whereIn('id', [1, 2, 3])->get();

(4) Sorting

$users = User::orderBy('name', 'desc')->get();

(5) Query the specified column

$users = User::select('name', 'email')->get();

We can pass multiple parameters in the select method, each parameter represents the column to be queried The name.

(6) Limit the result set

$users = User::skip(10)->take(5)->get();

We can use the skip and take methods to implement paging. The skip method is used to skip a specified number of records, and the take method is used to return a specified number of records. .

(7) Using aggregate functions

$avg_age = User::avg('age');
$max_age = User::max('age');
$min_age = User::min('age');
$count = User::count();

We can use some aggregate functions, such as avg, max, min, count, etc.

  1. Update data

Using Eloquent ORM to update a record, we can first query the record and then call the save method on the model instance.

$user = User::find(1);
$user->name = 'John';
$user->save();

We can also use the update method to update multiple records:

User::where('active', 1)->update(['status' => 'inactive']);
  1. Delete data

Using Eloquent ORM to delete a record, we can first Query the record and then call the delete method on the model instance.

$user = User::find(1);
$user->delete();

We can also use the destroy method to delete multiple records:

User::destroy([1, 2, 3]);

This will delete records with IDs 1, 2 and 3.

  1. Summary

In this article, we introduced in detail how to use Eloquent ORM for database queries. Eloquent ORM is a very powerful and flexible tool in the Laravel framework, which can help us quickly build efficient and maintainable database queries. If you have any questions or comments about Eloquent ORM, please leave them in the comments.

The above is the detailed content of Laravel development: How to use Eloquent ORM for database query?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)