0
0
Laravelframework~30 mins

Query parameters in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Query Parameters in Laravel
📖 Scenario: You are building a simple Laravel web application that shows a list of products. You want to allow users to filter products by category using query parameters in the URL.
🎯 Goal: Build a Laravel route and controller method that reads a query parameter called category from the URL and returns only products matching that category.
📋 What You'll Learn
Create an array of products with exact keys and values
Add a variable to hold the query parameter value
Filter the products array using the query parameter
Return the filtered products in a Laravel controller method
💡 Why This Matters
🌍 Real World
Filtering data based on user input in URLs is common in web apps, such as showing products by category or articles by tag.
💼 Career
Understanding query parameters and filtering data is essential for backend developers working with Laravel or any web framework.
Progress0 / 4 steps
1
Create the products array
Create a PHP array called $products with these exact entries: ['id' => 1, 'name' => 'Laptop', 'category' => 'electronics'], ['id' => 2, 'name' => 'Chair', 'category' => 'furniture'], and ['id' => 3, 'name' => 'Smartphone', 'category' => 'electronics'].
Laravel
Need a hint?

Use a PHP array with three associative arrays inside, each representing a product.

2
Get the category query parameter
Create a variable called $category that gets the category query parameter from the Laravel request using request()->query('category').
Laravel
Need a hint?

Use Laravel's request()->query('category') to get the query parameter.

3
Filter products by category
Create a variable called $filteredProducts that filters $products to include only products where 'category' equals $category. Use array_filter with a callback function that checks $product['category'] === $category. If $category is empty, set $filteredProducts to $products without filtering.
Laravel
Need a hint?

Use array_filter with a callback that compares the product's category to $category. Use an if statement to check if $category is set.

4
Return filtered products in controller method
Create a Laravel controller method called showProducts that returns the $filteredProducts array as a JSON response using return response()->json($filteredProducts);. Include all previous code inside this method.
Laravel
Need a hint?

Wrap all code inside a controller method named showProducts. Use the Request object to get the query parameter and return JSON response.