Laravel Course

- Accessing Session Data
- Determining if a Session exists
- Storing data in Session
- Deleting Session
- Laravel Session in controller __construt()

Sessions are used to store informations across the requests. Laravel provides various drivers to store session data: file, cookie, apc, array, Memcached, Redis, and database.

Using Database Session Driver

When using the database session driver, you will need to create a table to contain the session items.
Below is an example Schema declaration for the 'session' table:
Schema::create('sessions', function ($table){
  $table->string('id')->unique();
  $table->unsignedInteger('user_id')->nullable();
  $table->string('ip_address', 45)->nullable();
  $table->text('user_agent')->nullable();
  $table->text('payload');
  $table->integer('last_activity');
});
You may use the session:table Artisan command to automatically generate this migration:
php artisan session:table

php artisan migrate

Accessing Session Data

To access data stored in session, you can use the session() method of the Request instance, or the global session() helper.

Accessing the session via a Request instance

After getting the Request instance, we can use the get('sesion_name') method to get the session data.
$value = $request->session()->get('key');
You may also pass a default value as the second argument to the get() method, to be returned if the specified key does not exist in the session.
You can also pass a function as the default value:
$value = $request->session()->get('key', 'default');

$value = $request->session()->get('key', function(){
  return 'default';
});
You can use the all() method to get an array with all session data.
$sess = $request->session()->all();

The Global session() function

Similar with the $request->session()->get('key') method, the session() function receives a string argument for the session key, and optional, a second argument for 'default' value:
Route::get('home', function(){
  //Retrieve the value of the session with key 'name'
  $value = session('name');

  //Specifying a default value
  $value = session('name', 'default');
});
By default, Laravel session expires after 120 minutes. To modify the session lifetime, open the config/session.php file, and change the value of the 'lifetime' key.

Determining if a Session exists

To determine if a Session exists and is not null, use the use() method:
if($request->session()->has('users')){
  //
}
To determine if a Session is present, even if its value is null, you may use the exists() method:
if($request->session()->exists('users')){
  //
}

Storing data in Session

To store data in session, you can use the put() method or the session() function.
- The put() method will take two arguments, the 'key' and the 'value':
$request->session()->put('key', 'value');
- When the session() helper is called with an array of key / value pairs, those values will be stored in the session:
session(['key'=> 'value']);

Deleting Session

To delete session, you can use one of these methods:


If you want to add the value of a session directly in blade template, you can use one of these formats:
@if(session('key'))  
 {{session('key')}}
@endif
Or:
{{session('key', '')}}

Practical example

1. We create a controller called SessionController.
Copy the following code and save it in "app/Http/Controllers/SessionController.php".
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class SessionController extends Controller {
  public function getSession(Request $request){
    if($request->session()->has('my_name')) return "Session 'my_name' = ". $request->session()->get('my_name');
    else return 'No data in session';
  }

  public function putSession(Request $request){
    $request->session()->put('my_name','Mar Plo');
    return 'Data has been added to session "my_name"';
  }

  public function deleteSession(Request $request){
    if($request->session()->has('my_name')) $request->session()->forget('my_name');
    return 'my_name session has been deleted.';
  }
}
2. Now, set up the routes to test the SessionController.
Add the following code in the routes/web.php file:
Route::get('session/get','SessionController@getSession');
Route::get('session/put','SessionController@putSession');
Route::get('session/delete','SessionController@deleteSession');
3. Visit the following URL to add data in session:
//localhost:8000/session/put
- Output:
Data has been added to session "my_name"
4. Visit the following URL to get data from session:
//localhost:8000/session/get
- Output:
Session 'my_name' = Mar Plo
5. Visit the following URL to delete "my_name" session:
//localhost:8000/session/delete
- Output:
my_name session has been deleted.
6. Now, if you visit again the URL: //localhost:8000/session/get , it will display:
No data in session

Laravel Session in controller __construt()

Laravel Sessions are initiated in middleware; the session cannot be directly accessed in controller's constructor because the middleware has not run yet.
To use Session in controller's __construt(), use the $this->middleware(Callback) method directly in your constructor, and work with Session in the "Callback" function passed as argument.
public function __construct(){
  $this->middleware(function($request, $next){
    //Your code with Session ..

    return $next($request); //<- this is required
  });
}

- Documentation: Laravel - Sessions

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
Sessions

Last accessed pages

  1. Node.js Move and Copy Directory (19977)
  2. addChild and removeChild (7900)
  3. Drag and Drop with jQuery UI (6798)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (68949)
  5. JavaScript Scripts (2883)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (306)
  2. Read Excel file data in PHP - PhpExcelReader (108)
  3. The Four Agreements (93)
  4. PHP Unzipper - Extract Zip, Rar Archives (90)
  5. The Mastery of Love (84)
Chat
Chat or leave a message for the other users
Full screenInchide