Session Laravel

How to work with sessions, store session variables, retrieve them, etc. in the PHP Laravel framework with request and the global session helper.

Session variables are one of the main tools that we have, in server-side web development, to store data that lasts throughout the different requests or requests made during the visit to a site.

They are very useful because the HTTP protocol is not aware per se that multiple requests are part of the same user visit. Thanks to session variables, the server is able to relate one request to another and store data throughout it.

Unlike per-database persistence, session variables are perishable, so they disappear after a while has passed without a new request being made by that same browser. But even with this volatility, it is very useful to do things like, for example, store the products that are inserted in a shopping cart.

PHP already has a “native” handling of session variables. However, it is a bit stiff. Laravel proposes different mechanisms, at a slightly higher level, and with more detailed configuration possibilities. In this article we will give some essential guides to be able to use sessions in Laravel, although it is always interesting to keep in mind the documentation of the version you are using in your case. We are now on Laravel 5.8.

Session system configuration

The configuration of the HTTP Session system is done in the config/session.php file. It is here where we say which is the support where the sessions are going to be stored, for how long, etc.

As we said, the main novelty of the Laravel session system with respect to native PHP is the ease with which we can alter the internal functioning of the sessions, to define a diverse storage support. The main options are the following:

  • file – Session variables are stored in files, on the path: storage/framework/sessions.
  • cookie – Session variables are stored in cookies in the browser, properly encrypted.
  • database – Sessions are implemented in the database. Attention, because this configuration requires that certain migrations be executed to have the storage tables.
  • memcached / redis – This support allows you to use an in-memory caching system, faster than other alternatives.

The sessions configuration file is pretty self-explanatory. A quick glance will allow you to configure the session system. By default Laravel uses the file system. It is important that you read the documentation carefully if you want to change this support, to know the requirements of the one you want to configure.

Mechanisms for accessing the Laravel session system

Unlike when we work directly with PHP sessions, Laravel takes care of various administrative operations, such as opening the session when a request is executed. Therefore, we can use the session variables at any time we want.

To begin you should know that there are two alternatives to access the necessary functions to work with the session.

Helper global session

This helper allows you to access the API for session access from anywhere in your code, even from views if necessary. It is the most convenient way to access session data, modify it, etc.

For example, this is how we can access a session variable called “idCart”.

$cart_identifier = session(‘idCart’);

An instance of Request

From the Laravel Request object we can also access the sessions API. This alternative therefore requires having a $request object, which we have already discussed on other occasions in the . This object, for example, can be injected into a method of a controller.

This would be the code of a controller method. You can see how the injection of the $request object is declared as a parameter. Once we have the request, we can get an “idCart” session variable like this.

public function index(Request $request) { $cart_identifier = $request->session()->get(‘idCart’); // Rest of your controller code… }

You just have to keep in mind that the mechanisms for accessing the session data vary a little from one working model to another. In the future we are going to show code accessing the global helper, since it is more universal and you can use it without any ceremony from any part of your application.

Create and retrieve session variables with Laravel

Now let’s see different operations that can be done with the sessions, with the working mode allowed by the session helper.

Store a session variable

We simply tell it in an associative array which session variables we want to store. This array contains key/value pairs. The key indicates the name of the variable and the value its value.

session();

Retrieve a session variable

The helper allows us to recover data stored in the session in a very comfortable way, simply indicating the name of the variable we want to access.

$stored_value = session(‘idCart’);

session object

Some session operations are performed by accessing a “session” object, from which we have access to various utility methods.

The session object is obtained by executing the global helper without sending any parameters to it.

session()

Often that session object is used without needing to store it in any variable, directly hooking the method you want to execute. For example one of the following.

Clear a session variable

Using the session object we can tell Laravel to clear a session variable. We use the forget() method for this, like this:

session()->forget(‘orderId’);

Check for the existence of a session variable

Sometimes it is necessary to know if a certain variable exists in the Laravel session system. To do this we use the has() method.

session()->has(‘paymentIntentId’);

Regenerate session identifier

The session identifier allows Laravel, and ourselves, to identify a user’s session on the page.

Each session has its identifier, which is kept throughout the entire visit. However, when a user logs into the system, with their user data, this identifier is automatically regenerated.

This is a default functionality in Laravel, but if for any reason you need to manually regenerate it, you can also do it from the regenerate() method.

session()->regenerate();

Clear session data on logout

Although logging out might assume that session data should be cleared, this is not a default behavior in Laravel, at least not in all versions.

If we do not want to manually modify the login system already implemented by Laravel, we can carry out a simple operation, which basically consists of generating an event handler for “Logout”.

This is declared in the app/Providers/EventServiceProvider.php file using the $listeners array.

protected $listen = , ];

Through the above code we are indicating that when the “Logout” event is fired, the DeleteSessionData handler is invoked.

That handler can be auto-generated thanks to an Artisan command. You have to execute this generation command after having edited the EventServiceProvider.php and it is in charge of creating the scaffolding of all the necessary classes that are being used to manage events.

php artisan event:generate

Note: You do not indicate anything else to the previous command. That is, you don’t have to specify which handlers or events should be generated, as you infer it from the EventServiceProvider.php file. Of course artisan will leave those classes that have already been created untouched.

The DeleteSessionData class, once generated and edited, will have code like this:

forget(‘session_variable_you_want_to_make_sure_to_delete’); } }

conclusion

So far we have seen a good part of the utilities and functions of the Laravel session system. We have even been able to discover something extra that is not explained, such as the possibility of eliminating certain sensitive session variables, which we do not want to continue knowing after the user has logged out.

However, the Laravel framework has many other utilities for working with sessions. We always recommend studying the documentation to learn more about all these things. Remember to continue learning also in the .

See also  Files with UTF-8 encoding to save an XML
Loading Facebook Comments ...
Loading Disqus Comments ...