# Query Builder in Laravel

What is the Query Builder in Laravel?

The Query Builder in Laravel provides a fluent interface for building and executing database queries. It offers an alternative to raw SQL and Eloquent ORM, making it ideal for complex or custom queries.

---

## Origin

The Query Builder has been a part of Laravel since its inception, designed to simplify interacting with databases by providing an intuitive API.

---

## Why is the Query Builder Used?

1. **Flexibility**: Allows fine-grained control over database queries.
2. **Database Agnostic**: Supports multiple database systems like MySQL, PostgreSQL, and SQLite.
3. **Improved Readability**: Provides a fluent syntax for constructing complex queries.

---

## Best Practices

1. **Use Bindings**: Prevent SQL injection by using parameter bindings.
2. **Leverage Aggregates**: Use methods like `count` and `sum` for efficient data retrieval.
3. **Optimize Queries**: Combine queries using joins or subqueries for better performance.

---

## Example in Action

Retrieve data using the Query Builder:

```php
use Illuminate\Support\Facades\DB;

$users = DB::table('users')
    ->where('status', 'active')
    ->orderBy('created_at', 'desc')
    ->get();
```

Insert data:

```php
DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'status' => 'active',
]);
```

Read this definition in a browser: https://ranetrace.com/glossary/query-builder-in-laravel
