Laravel Basic Tutorial-Session

Source: Internet
Author: User

Session

Brief introduction

Because the HTTP driver is a stateless protocol, this usually means that the server does not clearly know the relationship between the current requesting user and the previously requested user, and the Session provides a solution for this cross-requesting user. Laravel comes with a simple, unified API to support a variety of back-end session drivers. Laravel provides out-of-the-box support for the popular backend driver for Memcached,redis and databases.

Configuration

The session configuration file is stored in the config/session.php. You should make sure to read the configuration item comments in the file before using it. Laravel each item in the configuration is commented in detail. By default, the Laravel configuration uses the file session driver, which is sufficient for most applications. However, in a production environment, it is recommended to use memcached or Redis as a memory-level driver, which can be a significant boost to the session performance of the application.

The session data for each request is stored in the location of the session driver where you defined it. The following drivers can be used out of the box in Laravel:

    • The file-sessions is stored in the storage/framework/sessions.
    • Cookie-sessions will be stored in securely encrypted cookies.
    • Database-sessions will be stored in the database used in your app.
    • The memcached/redis-sessions will be stored in a faster memory-level storage driver.
    • Array-sessions is simply stored in an array of PHP, and it cannot be accessed across requests.

Note: The array driver is typically used for testing to avoid persistent session data.

Driver Prerequisites

Database

When using the database session driver, you need to create a table to store the session entries. The following example is the schema declaration for the database Session driver table:

Schema::create (' Sessions ', function ($table) {  $table->string (' id ')->unique ();  $table->integer (' user_id ')->nullable ();  $table->string (' IP_Address ', ()->nullable ();  $table->text (' user_agent ')->nullable ();  $table->text (' payload ');  $table->integer (' last_activity ');});

You can also use the session:table Artisan command to generate a database session-driven migration table:

PHP artisan session:tablecomposer dump-autoloadphp Artisan Migrate

Redis

Before using the Redis session driver, you need to install Predis/predis (~1.0) via Composer.

Other Session considerations

Flash is used inside the Laravel framework as a key in the session, so you should avoid using the name key to the session.

If you need to store the session data after secure encryption, you can set the Encrypt option to true in the configuration file.

Basic usage

Visit Session

First, let's go to the session. We can access an instance of the session through an HTTP request. HTTP requests can be injected by using type hints in the Controller method. You should remember that the dependency of the Controller method is injected through the Laravel service container:

 
  Session ()->get (' key ');     //   }}

When you retrieve a value from the session, you can also specify a default value to the second parameter of the Get method, and the default value is returned when the session does not retrieve the value of the corresponding key. You can also pass Closure as the default value, and if the corresponding key is not found, the value returned by the Closure execution will be the default value:

$value = $request->session ()->get (' key ', ' Default '), $value = $request->session ()->get (' key ', function () {  return ' default ';});

If you want to retrieve all the values from the session, you can use the All method:

$data = $request->session ()->all ();

You can use the Global helper method session to retrieve and store values:

Route::get (' Home ', function () {  //Retrieve a piece of data from the session ...  $value = Session (' key ');  Store a piece of data in the session  ... session ([' key ' = ' value ']);});

Determine if there is an item in the session

You can use the has method to determine if a session contains an item, and if it does, returns true:

if ($request->session ()->has (' user ')) {  //}

storing data in session

Once you get an instance of the session, you have the ability to interact with the underlying data, and you can interact with the various instances. For example, you can use the Put method to store a new data item in the session:

$request->session ()->put (' key ', ' value ');

Pushes content to an array of items in the session

You can use the push method to push a new value into an array of values in the session. For example, if the User.teams key indicates the path of the array in the session, you can push the new value into the array like this:

$request->session ()->push (' User.teams ', ' developers ');

Retrieving and deleting an item

The Pull method deletes the item in the session at the same time it is retrieved:

$value = $request->session ()->pull (' key ', ' default ');

Delete an item in the session

You can use the Forget method to delete an item in the session, and if you want to remove all the data from the session, you can use the Flush method:

$request->session ()->forget (' key '), $request->session ()->flush ();

Regenerate session ID

If you need to regenerate the session ID, you can use the Regenerate method:

$request->session ()->regenerate ();

Flash data

Sometimes you want to store some data in the session, but only allow the next request, and then eliminate it. Then you can use the Flash method. The data stored in the session can only be accessed in subsequent requests and deleted later. Flash data is typically used to make some temporary status messages:

$request->session ()->flash (' status ', ' Task was successful! ');

If you need to maintain the flash data to more requests, you can use the Reflash method, which will maintain all the flash data into the additional requests. If you only need to maintain the specified flash data, you can use the Keep method:

$request->session ()->reflash (), $request->session ()->keep ([' username ', ' email ']);

Add a custom Session driver

You need to use the Extend method of the session mask to add additional session drivers to Laravel. You can call the Extend method in the service provider's boot method:

    

You should be aware that your custom session driver should implement the Sessionhandlerinterface interface. The interface contains only a few simple methods that need to be implemented. An implemented MongoDB driver structure should look like the following:

     

Because these methods are not as difficult to understand as cached storeinterface. So, let's take a quick look:

    • The Open method is typically used for file-based session storage systems. Since the laravel already comes with the file session driver, you hardly need to add any code to this method. You can place it directly as an empty method. In fact, this is a poor interface design (we'll discuss it later), and PHP has to implement this method.
    • The Close method, like the open method, you can also ignore it, and for most drivers it is not needed at all.
    • The Read method should return the string version of the associated data in the session based on the given $sessionId. You do not need to do any serialization or other encoding operations on storage or retrieval, as Laravel will perform serialization services for you.
    • The Destroy method should remove the associated data from the session store.
    • The GC method should delete the expired data associated with the session based on the given $lifetime UNIX timestamp. For systems that have automatic expiration capabilities, such as Memcached and Redis, you can simply leave this method empty.

Once your session driver is registered. You can use the MONGO driver in the config/session.php configuration file.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.