0
0
Laravelframework~30 mins

Raw expressions in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Raw Expressions in Laravel Queries
📖 Scenario: You are building a Laravel application that needs to query a database table called products. You want to select products with a price greater than a certain value, but also want to use a raw SQL expression to calculate a discounted price on the fly.
🎯 Goal: Build a Laravel query using raw expressions to calculate a discounted price for products and filter products by price.
📋 What You'll Learn
Create a products array with sample product data
Define a minPrice variable to filter products
Use Laravel's DB::raw() to calculate a discounted price
Write a query that selects product name and discounted price
Filter products where price is greater than minPrice
💡 Why This Matters
🌍 Real World
Raw expressions let you write custom SQL inside Laravel queries, useful for calculations or database-specific functions not directly supported by Laravel's query builder.
💼 Career
Understanding raw expressions is important for backend developers working with Laravel to optimize queries and implement complex database logic efficiently.
Progress0 / 4 steps
1
Create the products data array
Create a PHP array called products with these exact entries: ['name' => 'Laptop', 'price' => 1200], ['name' => 'Phone', 'price' => 800], and ['name' => 'Tablet', 'price' => 600].
Laravel
Need a hint?

Use a PHP array with associative arrays for each product.

2
Define the minimum price filter
Create a variable called minPrice and set it to 700 to filter products with price greater than this value.
Laravel
Need a hint?

Just assign 700 to a variable named minPrice.

3
Write the query with raw discounted price
Write a Laravel query using DB::table('products') that selects name and a raw expression for discounted price as price * 0.9 named discounted_price. Use DB::raw() for the raw expression. Filter products where price is greater than minPrice.
Laravel
Need a hint?

Use DB::raw('price * 0.9 as discounted_price') inside select() and filter with where('price', '>', $minPrice).

4
Complete the query by getting results
Complete the query by calling get() on the $query variable to retrieve the filtered products with discounted prices.
Laravel
Need a hint?

Call get() on $query and assign to $results.