Mahmoud Abd AL Kareem
Mahmoud Abd AL Kareem

Reputation: 645

Global variables in laravel 5.2 controllers

I want a variable to be shared by other controller methods. This variable can be updated by one controller method and the change should be reflected in other methods? any suggestions ? what is the best practice to do that ? this is my code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Session;

class test extends Controller
{


public $global;

public function __construct()




 public function a(Request $request){


 $this->global="some value"

 }

 public function b(Request $request){

  echo $this->global;
  //it always return a null 

 }



  }

Upvotes: 3

Views: 10787

Answers (2)

Abhishek
Abhishek

Reputation: 3967

Set the variable inside your constructor.

function _construct() { $this->global = "some value";} 

So, you don't only want a global variable, you also want that this variable should be changed by other routes as well. The one way to achieve this is using session.

function a() {
    session()->put('global_variable', 'set by method a');
    //your other logic
}

and from method b...

function b() {
    //get the variable set by method a here
    dd(session()->get('global_variable'));
}

Upvotes: 5

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can create a new file in config and use

config('your_new_file_name.key')

Check this : https://laracasts.com/discuss/channels/general-discussion/laravel-5-global-variables

Upvotes: 3

Related Questions