0
0
Laravelframework~5 mins

Where clauses in Laravel

Choose your learning style9 modes available
Introduction

Where clauses help you filter data from the database by setting conditions. They let you get only the records you want.

When you want to find users older than 18 years.
When you need to get all products that are in stock.
When you want to search posts with a specific title.
When you want to filter orders by status like 'completed'.
When you want to get records created after a certain date.
Syntax
Laravel
DB::table('table_name')->where('column', 'operator', 'value')->get();

The operator is optional and defaults to '=' if not provided.

You can chain multiple where clauses to add more conditions.

Examples
Gets all users older than 18.
Laravel
DB::table('users')->where('age', '>', 18)->get();
Gets all products where in_stock is true (1).
Laravel
DB::table('products')->where('in_stock', 1)->get();
Gets posts with titles containing 'Laravel'.
Laravel
DB::table('posts')->where('title', 'like', '%Laravel%')->get();
Gets completed orders with total greater than 100.
Laravel
DB::table('orders')->where('status', 'completed')->where('total', '>', 100)->get();
Sample Program

This code fetches users older than 25 and prints their names and ages.

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

// Get all users with age greater than 25
$users = DB::table('users')->where('age', '>', 25)->get();

foreach ($users as $user) {
    echo "User: {$user->name}, Age: {$user->age}\n";
}
OutputSuccess
Important Notes

You can use orWhere to add alternative conditions.

Use whereNull or whereNotNull to check for null values.

Remember to import DB facade to use query builder.

Summary

Where clauses filter data by conditions.

You can chain multiple where clauses for complex filters.

They help get only the data you need from the database.