0
0
Laravelframework~30 mins

Query scopes in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Query Scopes in Laravel
📖 Scenario: You are building a Laravel application to manage a list of books in a library. You want to easily filter books that are published and those that are popular.
🎯 Goal: Create a Laravel Eloquent model with query scopes to filter published books and popular books. Then use these scopes to get filtered lists.
📋 What You'll Learn
Create a Book model with a published boolean field and a popularity integer field.
Add a query scope called scopePublished to filter books where published is true.
Add a query scope called scopePopular to filter books where popularity is greater than 100.
Use the query scopes to get all published books and all popular books.
💡 Why This Matters
🌍 Real World
Query scopes are used in Laravel applications to keep database queries clean and reusable, especially when filtering data based on common conditions like status or popularity.
💼 Career
Understanding query scopes is important for Laravel developers to write maintainable and efficient database queries in real-world projects.
Progress0 / 4 steps
1
Create the Book model with fields
Create a Laravel Eloquent model class called Book with public properties published and popularity. Initialize published to true and popularity to 120 inside the constructor.
Laravel
Need a hint?

Define public properties published and popularity in the Book class. Set their values in the constructor.

2
Add the published query scope
Add a public method called scopePublished to the Book model. It should accept a $query parameter and return the query filtered where published is true using where('published', true).
Laravel
Need a hint?

Define scopePublished method that filters the query where published is true.

3
Add the popular query scope
Add a public method called scopePopular to the Book model. It should accept a $query parameter and return the query filtered where popularity is greater than 100 using where('popularity', '>', 100).
Laravel
Need a hint?

Define scopePopular method that filters the query where popularity is greater than 100.

4
Use the query scopes to get filtered books
Write two lines of code to get all published books using Book::published()->get() and all popular books using Book::popular()->get(). Assign the results to variables $publishedBooks and $popularBooks respectively.
Laravel
Need a hint?

Use the query scopes by calling Book::published()->get() and Book::popular()->get(). Assign results to $publishedBooks and $popularBooks.