Laravel Query Examples
October 8, 2024 · AI Conversations
### Basic Query Example
// Fetch all records from the 'users' table
$users = User::all();
### Query with Conditions
// Fetch users where 'status' is 'active'
$activeUsers = User::where('status', 'active')->get();
### Query with Multiple Conditions
// Fetch users where 'status' is 'active' and 'age' is greater than 25
$filteredUsers = User::where('status', 'active')
->where('age', '>', 25)
->get();
### Query with Pagination
// Fetch users with pagination (10 users per page)
$users = User::paginate(10);
### Query with Relationships (Eager Loading)
// Fetch users along with their associated posts (assuming a relationship exists)
$usersWithPosts = User::with('posts')->get();
### Query with Sorting and Limits
// Fetch the top 5 users sorted by 'created_at' in descending order
$topUsers = User::orderBy('created_at', 'desc')->take(5)->get();
These are some common examples of Laravel queries using Eloquent. You can easily modify them based on your specific needs. Let me know if you need more advanced examples!
### Example with `toSql()` Method
// Example of a basic query
$query = User::where('status', 'active');
// Print the raw SQL query
dd($query->toSql());
This will output the raw SQL query as a string, something like:
select * from `users` where `status` = ?
### Binding Values with `getBindings()`
If you want to see the full query with bound values, you can use `getBindings()` along with `toSql()`.
$query = User::where('status', 'active');
// Print the raw SQL query and bindings
dd($query->toSql(), $query->getBindings());
This will show the SQL query and an array of the bound values for the placeholders:
select * from `users` where `status` = ?
Array
(
[0] => active
)
To combine the query with bindings for better readability:
$sql = str_replace_array('?', $query->getBindings(), $query->toSql());
dd($sql);
Let me know if you need more!