Sharing variables between functions in the controller

0

I have a function in my controller that receives some requests, and in the end everything is stored in two arrays. In this function, if I do the following:

 return view('negocio.detalhes-trajetoa', compact('arrayLogradourosA', 'arrayLogradourosB'));

I can access these two arrays in this view.

But my goal is to pass these two arrays to another function of my controller, to look like this:

public function outraFuncao () {
    return view('negocio.detalhes-trajetoa', compact('arrayLogradourosA', 'arrayLogradourosB'));
}

But as these two arrays are in another function of my controller, in my view it gives that error "Undefined variable".

How can I share these two arrays for another function in my controller ??

    
asked by anonymous 03.06.2018 / 23:31

2 answers

1

The function compact only works with local scope variables.

To reuse these variables you need to pass them to the new method.

public function routeEndpoint() {
    // ..

    return $this->outraFuncao($arrayLogradourosA, $arrayLogradourosB);
}

private function outraFuncao ($arrayLogradourosA, $arrayLogradourosB) {
    return view(
        'negocio.detalhes-trajetoa', 
        compact('arrayLogradourosA', 'arrayLogradourosB')
    );
}

So I understand this second method is used internally by the other endpoints of controller routes. So its visibility does not have to be public and in the example I changed it to private .

    
04.06.2018 / 03:00
0

Look, you can define global variables in your controller:

class TestController extends Controller
{
    private $arrayLogradourosA;
    private $arrayLogradourosB;

    public function funcao1($cidade, $cidade2)
    {
        $this->$arrayLogradourosA = Logradouros::where('cidade', $cidade)->get();
        $this->$arrayLogradourosB = Logradouros::where('cidade', $cidade2)->get();
    }

    private function outraFuncao() { 
        $arrayLogradourosA = $this->arrayLogradourosA;
        $arrayLogradourosB = $this->arrayLogradourosB;

        return view(
            'negocio.detalhes-trajetoa', 
            compact('arrayLogradourosA', 'arrayLogradourosB')
        );
    }
}

It's a generic example, because I did not really understand why it was not all in one function.

    
20.11.2018 / 17:27