0
0
Laravelframework~30 mins

Cookie handling in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Cookie Handling in Laravel
📖 Scenario: You are building a simple Laravel web application that tracks user preferences using cookies. Cookies help remember user choices even after they leave the site.
🎯 Goal: Create a Laravel controller that sets a cookie named user_theme with the value dark, reads this cookie, and returns a response showing the cookie value.
📋 What You'll Learn
Create a Laravel controller named CookieController.
Set a cookie named user_theme with the value dark that lasts 60 minutes.
Read the user_theme cookie from the request.
Return a response that includes the cookie value.
💡 Why This Matters
🌍 Real World
Cookies are used in web apps to remember user preferences like themes, language, or login sessions. This project shows how to set and read cookies in Laravel to personalize user experience.
💼 Career
Understanding cookie handling is essential for backend developers working with Laravel to manage user sessions, preferences, and authentication securely and efficiently.
Progress0 / 4 steps
1
Create the CookieController with a method to set a cookie
Create a Laravel controller class named CookieController with a public method setCookie that returns a response with the text 'Cookie has been set'.
Laravel
Need a hint?

Define a class named CookieController extending Controller. Add a public method setCookie that returns a response with the text 'Cookie has been set'.

2
Add a cookie variable with name, value, and duration
Inside the setCookie method, create a variable named $cookie that stores a cookie with the name 'user_theme', value 'dark', and duration 60 minutes using Laravel's cookie() helper.
Laravel
Need a hint?

Use $cookie = cookie('user_theme', 'dark', 60); to create the cookie variable inside the setCookie method.

3
Attach the cookie to the response
Modify the setCookie method to attach the $cookie variable to the response using the withCookie() method before returning it.
Laravel
Need a hint?

Use return response('Cookie has been set')->withCookie($cookie); to attach the cookie to the response.

4
Create a method to read the cookie and return its value
Add a public method getCookie in CookieController that accepts a Request $request parameter, reads the 'user_theme' cookie using $request->cookie('user_theme'), and returns a response with the text 'User theme is: ' followed by the cookie value.
Laravel
Need a hint?

Define getCookie(Request $request) method. Use $request->cookie('user_theme') to read the cookie. Return a response with the cookie value.