Laravel Query Examples

User
display laravel query
Assistant
Here’s an example of a Laravel query to fetch data from a database using Eloquent:

### 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!

User
print raw query laravel
Assistant
In Laravel, you can use the `toSql()` method to print the raw SQL query generated by Eloquent. Here’s an example:

### 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!

Leave a Comment

Your email address will not be published. Required fields are marked *