[php] Set session variable in laravel

I would like to set a variable in the session using laravel this way

Session::set('variableName')=$value;

but the problem is that I don't know where to put this code, 'cause I would like to set it for one time (when the guest visite the home page or any other page)? The main idea is to use a global variable to use it in all application controllers, I heared about something related to configuration variables but I'm not sure if it will be a good Idea to use config variables or only the session? Thanks

The answer is


php artisan make:controller SessionController --plain

Then

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class SessionController extends Controller {
   public function accessSessionData(Request $request) {
      if($request->session()->has('my_name'))
         echo $request->session()->get('my_name');
      else
         echo 'No data in the session';
   }
   public function storeSessionData(Request $request) {
      $request->session()->put('my_name','Ajay kumar');
      echo "Data has been added to session";
   }
   public function deleteSessionData(Request $request) {
      $request->session()->forget('my_name');
      echo "Data has been removed from session.";
   }
}
?>

And all route:

Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');

More Help: How To Set Session In Laravel?


to set session you can try this:

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

also to get session data you can try this:

$request->session()->get('key');

If you want to get all session data:

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

For example, To store data in the session, you will typically use the putmethod or the session helper:

// Via a request instance...
$request->session()->put('key', 'value');

or

// Via the global helper...
session(['key' => 'value']);

for retrieving an item from the session, you can use get :

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

or global session helper :

$value = session('key', 'default value');

To determine if an item is present in the session, you may use the has method:

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

In Laravel 6.x

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session


I think your question ultimately can be boiled down to this:

Where can I set a long-lived value that is accessible globally in my application?

The obvious answer is that it depends. What it depends on are a couple of factors:

  • Will the value ever be different, or is it going to be the same for everybody?
  • How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)

Config

If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:

<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')

Session

If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session. This is what you allude to in your question, but you are using incorrect syntax. The correct syntax to store a variable in Session is:

Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:

Session::get('somekey');

As far as when to perform these operations, that's a little up to you. I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:

// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point. 
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});

In Laravel 5.6, you will need to set it as

  session(['variableName'=>$value]);

To retrieve it is as simple as

$variableName = session('variableName')

You can try

 Session::put('variable_Name', "Your Data Save Successfully !");  
 Session::get('variable_Name');

To add to the above answers, ensure you define your function like this:

public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:

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

And retrieve the session in this way:

$data = $request->session()->get('key');

To erase the session try this:

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

or

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

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to session-variables

Local storage in Angular 2 Set session variable in laravel Session variables not working php Setting session variable using javascript How to use sessions in an ASP.NET MVC 4 application? Check if PHP session has already started How to use store and use session variables across pages? MySQL wait_timeout Variable - GLOBAL vs SESSION How do servlets work? Instantiation, sessions, shared variables and multithreading How to empty/destroy a session in rails?

Examples related to laravel-routing

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile] Laravel: How to Get Current Route Name? (v5 ... v7) Set session variable in laravel Laravel 5 - redirect to HTTPS How Can I Remove “public/index.php” in the URL Generated Laravel? Download files in laravel using Response::download Laravel Controller Subfolder routing My Routes are Returning a 404, How can I Fix Them?

Examples related to application-variables

Set session variable in laravel