0

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?

Alen
  • 1,221
  • 5
  • 21
  • 43
  • This will help you http://stackoverflow.com/questions/25189427/global-variable-for-all-controller-and-views – Onix Feb 22 '17 at 14:14

2 Answers2

3

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.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • How can I pass variable to __construct? – Alen Feb 22 '17 at 14:38
  • Normally you should do this when creating the object. However, with Laravel controllers this is not possible as far as I know. Maybe through injection. – Jerodev Feb 22 '17 at 15:11
2

I'm not sure if this is what you want but you can declare a protected or public variable in your Controller protected $id, then when you call store

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

And to use in other functions:

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

But this is only avaiable for the same instance of Controller, if you create a new instace of your Controller the variable $id will not be set until you call store method.

Nerea
  • 2,107
  • 2
  • 15
  • 14