How to set cookies in Laravel 10
If you are developing a website using Laravel 10, you might want to set cookies to store data on the client’s browser. Cookies are a great way to persist user data and provide a personalized experience for your users. In this article, we will go through the steps to set cookies in Laravel 10 using PHP and JavaScript.
Step 1: Create a cookie
To set a cookie in Laravel 10, you can use the cookie()
function provided by Laravel’s HTTP response object. You can add this function to your controller method to set a cookie. For example:
$cookie = cookie('name', 'John Doe', 60);
return response('Welcome to our website')->cookie($cookie);
This code sets a cookie named ‘name’ with the value ‘John Doe’ that will expire in 60 minutes.
Step 2: Access the cookie in JavaScript
Once the cookie is set, you can access it in JavaScript to perform client-side operations. You can use the document.cookie
property to access all cookies associated with the current document. For example:
console.log(document.cookie);
This will log all the cookies associated with the current document to the console.
Step 3: Modify the cookie
If you want to modify the value or expiration time of a cookie, you can set a new cookie with the same name, which will replace the existing one. For example:
$cookie = cookie('name', 'Jane Doe', 60);
return response('Welcome back')->cookie($cookie);
This code replaces the previously set ‘name’ cookie with the value ‘Jane Doe’ that will expire in 60 minutes.
Conclusion
Setting cookies in Laravel 10 is a simple process that can greatly enhance the user experience on your website. By persisting user data and providing personalized content, cookies can create a more engaging environment for your users. By following the steps outlined in this article, you can easily set and manage cookies in your Laravel 10 application.
promo sm 💃