How to use Laravel's Eloquent ORM to perform advanced database queries



Image not found!!

Laravel's Eloquent ORM (Object-Relational Mapping) provides a convenient and expressive way to interact with your database. It allows you to perform advanced database queries using a simple and intuitive syntax. Below are some examples of advanced queries you can perform with Eloquent:

1. Basic Querying:

php
// Retrieve all records from a table $users = User::all(); // Retrieve a specific record by ID $user = User::find(1); // Retrieve records based on a condition $admins = User::where('role', 'admin')->get();


2. Eager Loading:

Eager loading allows you to retrieve a model with its relationships in a single query, preventing the N+1 query problem.

php
// Retrieve users with their associated posts
$users = User::with('posts')->get();


3. Querying Relationships:

php
// Retrieve all posts of a specific user $posts = User::find(1)->posts; // Retrieve the user of a specific post $user = Post::find(1)->user;


4. Selecting Specific Columns:

php
// Retrieve only the name and email columns $users = User::select('name', 'email')->get();


5. Where Conditions:

php
// Retrieve users where the name is John $users = User::where('name', 'John')->get(); // Retrieve users where the name is like John $users = User::where('name', 'like', '%John%')->get();


6. Ordering and Limiting:

php
// Retrieve users ordered by name in descending order, limited to 10 $users = User::orderBy('name', 'desc')->take(10)->get();


7. Aggregates:

php
// Get the total number of users $count = User::count(); // Get the average age of users $averageAge = User::avg('age');


8. Subqueries:

php
// Retrieve users with posts created in the last month $users = User::whereHas('posts', function ($query) { $query->where('created_at', '>', now()->subMonth()); })->get();


Additional Links:

  1. 1. Laravel Eloquent Documentation
  2. 2. Laravel Eloquent Relationships
  3. 3. Laravel Query Builder
  4. 4. Laravel Eloquent Tips and Tricks

Remember to replace User and Post with your actual model names and adjust the examples to fit your specific database schema. Laravel's documentation is an excellent resource for more in-depth information and advanced use cases.



=== Happy Coding :)