Using basic sessions and cookies in laravel

There will be times when we want to pass data from one page of our app to another page
without needing to store the information in a database. To accomplish this, we can use the
various Session and Cookie methods that Laravel provides us.

Getting ready

For this recipe, we need a standard Laravel installation.

How to do it…

For this recipe, follow the given steps:
1. In the views folder, create a file named session-one.php with the following code:
<!DOCTYPE html>
<title>Laravel Sessions and Cookies</title>
<meta charset=”utf-8″>
<h2>Laravel Sessions and Cookies</h2>
<?= Form::open() ?>
<?= Form::label(’email’, ‘Email address: ‘) ?>
<?= Form::text(’email’) ?>
<?= Form::label(‘name’, ‘Name: ‘) ?>
<?= Form::text(‘name’) ?>
<?= Form::label(‘city’, ‘City: ‘) ?>
<?= Form::text(‘city’) ?>
<?= Form::submit(‘Go!’) ?>
<?= Form::close() ?>
2. In the routes.php file, create our routes as given in the following code:
Route::get(‘session-one’, function()
return View::make(‘session-one’);

Route::post(‘session-one’, function()
Session::put(’email’, Input::get(’email’));
Session::flash(‘name’, Input::get(‘name’));
$cookie = Cookie::make(‘city’, Input::get(‘city’), 30);
return Redirect::to(‘session-two’)->withCookie($cookie);
Route::get(‘session-two’, function()
$return = ‘Your email, from a Session, is ‘
Session::get(’email’) . ‘. <br>’;

$return .= ‘You name, from flash Session, is ‘
Session::get(‘name’) . ‘. <br>’;
$return .= ‘You city, from a cookie, is ‘ .
Cookie::get(‘city’) . ‘.<br>’;
$return .= ‘<a href=”session-three”>Next page</a>’;
echo $return;
Route::get(‘session-three’, function()
$return = ”;
if (Session::has(’email’)) {
$return .= ‘Your email, from a Session, is ‘ .
Session::get(’email’) . ‘. <br>’;
} else {
$return .= ‘Email session is not set.<br>’;
if (Session::has(‘name’)) {
$return .= ‘Your name, from a flash Session, is ‘ .
Session::get(‘name’) . ‘. <br>’;
} else {
$return .= ‘Name session is not set.<br>’;
if (Cookie::has(‘city’)) {
$return .= ‘Your city, from a cookie, is ‘ .
Cookie::get(‘city’) . ‘. <br>’;
} else {
$return .= ‘City cookie is not set.<br>’;
$return .= ‘<a href=”session-three”>Reload</a>’;
echo $return;

How it works…

To begin, we create a simple form that we will use to submit information to the sessions and
cookies. After posting the values, we take the email field and add it to a regular session. The
name field will be added to a flash session and the city will be added to a cookie. Also, we’ll
set the cookie to expire after 30 minutes. Once they’re all set, we redirect to our second page,
and make sure we pass the cookie to the return value.

Leave a Reply

Your email address will not be published. Required fields are marked *