0
0
Laravelframework~30 mins

OrWhere and advanced conditions in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Using OrWhere and Advanced Conditions in Laravel Queries
📖 Scenario: You are building a simple Laravel application to manage a bookstore's inventory. You want to find books that match certain conditions using Laravel's query builder.
🎯 Goal: Build a Laravel query that finds books where the author is 'John Doe' or the price is less than 20, using orWhere and advanced conditions.
📋 What You'll Learn
Create a query builder instance for the books table.
Add a where condition to find books with author equal to 'John Doe'.
Add an orWhere condition to find books with price less than 20.
Use a closure inside orWhere to add an advanced condition checking if published_year is greater than 2010.
💡 Why This Matters
🌍 Real World
Filtering database records with multiple conditions is common in web apps, like finding products, users, or posts matching complex rules.
💼 Career
Understanding Laravel's query builder and how to use orWhere and closures is essential for backend developers working with Laravel to build efficient and readable database queries.
Progress0 / 4 steps
1
Create the initial query builder for the books table
Create a variable called $query and set it to the Laravel query builder for the books table using DB::table('books').
Laravel
Need a hint?

Use DB::table('books') to start the query builder.

2
Add a where condition for author 'John Doe'
Add a where condition to $query to find books where the author column equals 'John Doe'.
Laravel
Need a hint?

Use where('author', 'John Doe') on the query builder.

3
Add an orWhere condition for price less than 20
Add an orWhere condition to $query to find books where the price column is less than 20.
Laravel
Need a hint?

Use orWhere('price', '<', 20) on the query builder.

4
Add an advanced orWhere condition with a closure for published_year
Add an orWhere condition to $query using a closure. Inside the closure, add a where condition to check if published_year is greater than 2010.
Laravel
Need a hint?

Use orWhere with a closure function that calls where('published_year', '>', 2010).