Search code examples
phplaravellaravel-5laravel-5.3

How to make a variable accessable to the whole controller in laravel


Lets say I have a

IndexController

Which contains a function

public function store($store)
{
    $store = (query)->get();
    return $store;
}

Now I want one column from store to be accessible to all functions like

$id = $store->id

I want it to be usable like this

public function abv()
{
    $categories = (query)->where('id','=',$id)->get();
}

My point is that it becomes a global variable to the whole controller. How do I achieve this?


Solution

  • You can set this value in the constructor of your controller as a private property.

    class MyController {
        private $id;
    
        public function __construct() {
            $this->id = (query)->get();
        }
    
        // More controller functions
    }
    

    Now any function in your controller will be able to call this property using $this->id.