, , ,


Get the book …

Get the Book…

Caveat: This post is outdated. Please visit the link above and get the new Laravel 5.8 book.

Time may come when you need to pass data without storing them into database or through any retrieval method from the database. Laravel ships with plenty of options. So you can pass data without any assistance from your database or Model ORM. With Session and Cookie, static methods solve this problem. But there is a caveat. It is not recommended to pass any secured data through this way. In that case the security can be breached. Since this book is primarily meant for the beginners, I would like to tell you something about the Session management. Presumably you already know what session is and HTTP is ultimately a stateless protocol. For the most part, a connection is broken down; when a call has been made to remote server. So it is really challenging how we can change this stateless condition to state full!

Session is a very straightforward way to maintain that state. We will see how it can be maintained and destroyed! Now it will be not out of context if I say some words about the client side. A web application has two distinct part – one is client side and the other is server side. When we pass data we often rely upon the server. But remember, server is on your side. The client has no headache about it. Your server has a memory and you can not play with it. It is precious. You can not do anything that would crash its memory!

My point is: the client side is vastly underutilized. In the present world many of them has high powered good processor and a few gigabytes of ram. But wait! Are not there DHTML, JavaScript, Ajax and HTML 5.0? Yes there are. But still for our coding practices it remains underutilized when the storing data is concerned. Now Laravel has used this Session and Cookie object in a very intelligent way. Session is coming down from the application. It can also be stored inside the database. But presently we are concerned about the application Session and Cookie object. When client sends her request throughout the forms to the server, we can just catch the data as an object. We can set the the Cookie time so that for 30 minutes or for one week it can stay inside the client’s computer and be updated. For our test purpose, we set it to only only one minute so that you can reload page after one minute and test it!
Let us start from our ‘routes.php’ where we want a form submission page.

Route::get('test/test', function() 
return View::make('test/test'); 

In the views folder we have a ‘test.blade.php’ page. The code is like this:

 Session and Cookie Test 
 Session and Cookie Test Page 


Submit Data

{!! Form::open([“url” => “testsessionandcookie”, “method” => “POST”]) !!}

{!! Form::label(‘name’, ‘Name’) !!} {!! Form::text(‘name’, null, [‘class’ => ‘form­control’])!!}
{!! Form::label(‘city’, ‘City’) !!} {!! Form::text(‘city’, null, [‘class’ => ‘form­control’])!!}

{!! Form::submit() !!} {!! Form::close() !!}

@stop @section(‘section­head2’) Second Heading @stop @section(‘content2’) Second content @stop @section(‘section­head3’) Third Heading @stop @section(‘content3’) Third content @stop

Now this form action will take place in the ‘routes.php’. So the next lines of codes are very important.


//testing session and cookie 
Route::get('test', function() 
return View::make('test'); 
Route::post('testsessionandcookie', function() 
Session::put('name', Input::get('name')); 
$cookie = Cookie::make('city', Input::get('city'), 
return Redirect::to('session­and­cookie­test')­ 
Route::get('session­and­cookie­test', function() 
    $return = 'Reload Now, You will Loose only 
Session data. ' . 'If you Reload after ONE minute, You 
will Loose Session & Cookie data both!'; 
$return .= 'Your user name, from a Session, is' . Session::get('name'); 
$return .= ' You city, from a cookie, is ' . 
Cookie::get('city') . '.

‘; $return .= ‘Reload‘; echo $return; }); Route::get(‘session­cookie­loss’, function() { $return = ”; if (Session::forget(‘username’)) { $return .= ‘Your name, from a Session, is ‘ . Session::get(‘name’) . ‘.
‘; } else { $return .= ‘User Name session is not set.
‘; } if (Cookie::has(‘city’)) { $return .= ‘Your city, from a cookie, is ‘ . Cookie::get(‘city’) . ‘.
‘; } else { $return .= ‘City cookie is not set.
‘; } ; $return .= ‘Back to Session and Cookie Test‘; echo $return; }); //session and cookie test ended

What I have shown is a very basic approach of how we can deal with session­and­cookie­test. But in reality, we need to take a closer look and dig much deeper to understand what is happening behind the scene. Let us discuss session in detail and see what Laravel 5 has for us in store. As I wrote earlier, Session is typically meant for storing information about the users across requests. Laravel ships with a variety of session back­ends that are available for use through the application. Support for popular back­ends like database, Memcached, Redis is also available.
The first part of the session is its configuration. So you need to have a look at the ‘config/session.php’ file and you find it very well documented. The line starts with this:
// config/session.php

Supported: “file”, “cookie”, “database”, “apc”,
“memcached”, “redis”, “array”
‘driver’ => env(‘SESSION_DRIVER’, ‘file’),

//end of line
As you find Laravel by default uses ‘file’ session diver. It works in most of the cases so I don’t think you need to change it unless it is urgently required. In production sometimes developers prefer Memcahced or Redis based session driver for faster performance. Now the session ‘driver’ defines where session data will be stored for each request. Laravel ships with several great drivers out of the box. By default it uses ‘file’ session driver but you can change it anytime. Let us see all the great staffs. First the ‘file’, in this case, sessions are stored in ‘storage/framework/sessions’. The second one is ‘cookie’. In this case, sessions are stored in secure, encrypted cookies. So you can keep them in a secured way.
The third and one of the most popular session driver is ‘database’. For database, sessions are stored in a database used by your application. We will see in a minute how we can store it in a database. The fourth one is also very popular among developers be it ‘memcached’ or ‘redis’ and the sessions are stored in one of these fast, cached based stores. We will discuss about Cache in detail later in this chapter.
The fifth and final one is our old friend ‘array’. In this case, sessions are stored in a simple PHP array and will not be persisted across requests. Now it is time for check the driver prerequisites. First we see how we can use the database session driver. To do that you need to make a session table in your database first.
php artisan session:table
Migration created successfully!
Now go to ‘database/migrations’ folder and find the required file to create the table:

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 
class CreateSessionTable extends Migration 
     * Run the migrations. 
     * @return void 
    public function up() 
        Schema::create('sessions', function 
(Blueprint $table) { 
     * Reverse the migrations.
     * @return void 
    public function down() 

Now you are all set to use the session table in your database. For the ‘Redis’ sessions with Laravel, you will need to install the ‘predis/predis’ package (~1.0) via Composer. Besides, please consult the documentation for further session prerequisites.
Let us see how session works. Consider a simple route like this:
Route::get(‘test’, ‘ContactController@test’);
And in the ‘ContactController’ test() method we have a code like this:

protected $request; 
public function __construct(Guard $auth, Request 
$request) { 
        $this­>request = $request; 
        $this­>auth = $auth; 
public function test() 
        $value = $this­>request­>session()­>all(); 

This is a very simple test to check what kind of session value being passed through the request­response chain when we type URL http://localhost:8000/test.
The output looks like this:

array:3 [▼
“_token” => “rUwPPBsMrbePLdlITrtGrLHBJnn7C2pCkuAWY5wp”
“_previous” => array:1 [▼
“url” => “http://localhost:8000”
“flash” => array:2 [▼
“old” => []
“new” => []

So whenever you request for a page there are some session values which are being shown above. We have accessed the session instance via HTTP request. Here we have retrieved all the session value by all() method. The Laravel framework uses the ‘flash’ session key internally, so you should not add an item to the session by that name. To retrieve a value from the session, you may also pass a default value as the second argument to the ‘get’ method. This default value will be returned if the specified key does not exist in the session.

$name = $this­>auth­>user()­>name; 
$value = $this­>request­>session()­>get('key', 

In the above code the output is the logged in user’s name. It is passed as a default value. The ‘forget’ method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the ‘flush’ method:
We have used this forget() method in our previous examples at ‘routes.php’ code:

Route::get('session­cookie­loss', function() 
$return = ''; 
if (Session::forget('name')) { 
$return .= 'Your name, from a Session, is ' . 
Session::get('name') . '. 
} else { 
$return .= 'User Name session is not set.
if (Cookie::has('city')) { 
$return .= 'Your city, from a cookie, is ' . 
Cookie::get('city') . '. 
} else { 
$return .= 'City cookie is not set.
$return .= 'Back to Session and 
Cookie Test'; 
echo $return; 

Finally a few words about using Session and Cookie. When you use what is very important according to the necessary steps your taking to build up your API. Both can accomplish same job – that is storing data across the web pages but the differences are enormous.
As you know, Cookie can store data for months if not years but session is not meant for that. Lifespan is important here. Another important factor is what you want to accomplish, what kind of job you are planning to do. Cookie works on Client so it is helpful for the situation where you have a cluster of web servers. You can communicate through that cluster ceaselessly. Since Session is stored on server it is difficult to work with one session data in that cluster of different web servers. But keeping sensitive data on Client side is by no means a very good idea. Client can anytime tamper with that data. Session data being stored on the server is safer for shopping basket like situation where Client can send her ID and the data is loaded through that local file. Matching is important here making data more secured. Client can not tamper with that data by hacking her browser. On the contrary Cookies stored in the browser can be tampered any time and Client can even make it disabled.
Another important thing about session data is you can make a session data as big as you want because it is stored on your server. But Cookie size is restricted by many browsers as some rogue web sites use them in a malicious manner eating up lot of gigabytes of storage space.
Finally, it is your choice to decide which one you prefer and for what purpose. Each have their own advantages and disadvantages. Do you want your data to work the next day when your visitor comes back next day, then your better choice is Cookie. But if you don’t need semi permanent data then session is always preferred. Session is always more secured and the control is at your hand. It is also easier to use and get cleaned up as soon as the visitor closes up her browser.
Laravel 5 has made your choice easier. Your choice is open. Session or Cookie, whatever you use, try to choose it keeping security in your mind. Never compromise your application’s security. If you handle sensitive data always store it in session and using database is the best choice.