0
0
Laravelframework~5 mins

Why Query Builder offers flexibility in Laravel

Choose your learning style9 modes available
Introduction

Query Builder lets you create database queries easily without writing raw SQL. It is flexible because you can build queries step-by-step and change them as needed.

When you want to build database queries dynamically based on user input.
When you need to join tables or add conditions without writing complex SQL.
When you want to keep your code clean and readable while working with databases.
When you want to avoid SQL injection by using safe query methods.
When you want to reuse parts of queries or add filters conditionally.
Syntax
Laravel
$query = DB::table('table_name')
            ->where('column', 'value')
            ->orderBy('column', 'asc')
            ->get();
You start with DB::table('table_name') to select the table.
You can chain methods like where(), orderBy(), and get() to build the query.
Examples
Get all records from the users table.
Laravel
$users = DB::table('users')->get();
Get users where the active column is 1.
Laravel
$activeUsers = DB::table('users')->where('active', 1)->get();
Get users ordered by name in descending order.
Laravel
$orderedUsers = DB::table('users')->orderBy('name', 'desc')->get();
Get users older than 18 with active status.
Laravel
$filteredUsers = DB::table('users')
    ->where('age', '>', 18)
    ->where('status', 'active')
    ->get();
Sample Program

This code fetches all users who are active and orders them by their name alphabetically. Then it prints each user's name on a new line.

Laravel
<?php
use Illuminate\Support\Facades\DB;

// Get all active users ordered by name
$users = DB::table('users')
    ->where('active', 1)
    ->orderBy('name', 'asc')
    ->get();

foreach ($users as $user) {
    echo $user->name . "\n";
}
OutputSuccess
Important Notes

Query Builder protects against SQL injection by binding parameters safely.

You can add conditions dynamically by checking variables before chaining where() methods.

Query Builder works with many database types supported by Laravel.

Summary

Query Builder helps build database queries step-by-step.

It is flexible because you can add or change parts of the query easily.

It keeps your code safe and readable without writing raw SQL.