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:
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();
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();
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;
php// Retrieve only the name and email columns
$users = User::select('name', 'email')->get();
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();
php// Retrieve users ordered by name in descending order, limited to 10
$users = User::orderBy('name', 'desc')->take(10)->get();
php// Get the total number of users
$count = User::count();
// Get the average age of users
$averageAge = User::avg('age');
php// Retrieve users with posts created in the last month
$users = User::whereHas('posts', function ($query) {
$query->where('created_at', '>', now()->subMonth());
})->get();
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 :)