Sharing variables between functions in the controller

Asked

Viewed 851 times

0

I have a function in my controller that receives some requests, and in the end everything is stored in two arrays. In this role, 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 gives that error "Undefined variable".

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

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')
    );
}

From what I understand this second method is used internally by others endpoints of routes of controller. Soon its visibility does not need to be published and in the example I changed to private.

  • What about Santos, all right? Nice answer, but the problem is that my first function, in your example, routeEndpoint() it already returns data to another view, if I put this Return, it does not work. There is another way to send these two arrays to another()?

  • in an easy way, no. One method is dependent on the other.

0

Look, you can set 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 didn’t really understand why it wasn’t all in one function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.