Pick up the return from one function to another in the Laravel controller

Asked

Viewed 694 times

2

I have two functions in the controller and need to pass the return of a function to the other and save in a variable, but is giving error.

function that returns

public function getarrcontatos(Request $request){
        $value = $request->get('value');
        $ArrContatos = [];
        $ArrContatos = $value;
        return ($ArrContatos);

    }

Function it receives

    public function store(Request $request){

          $input = $request->all();
          $obscontatos = $request->input('obscontatos');
          $result = count($obscontatos);



        for ($i = 0; $i < $result ; $i++) {


          $listacontatos = getarrcontatos();


        $contatoarray = array('idContato'=>$listacontatos[1],'ccContato'=>$listacontatos[2], 'idObsContato'=>$listacontatos[0]); 
       DB::table('contatoObsCc')->insert($contatoarray);

      }

  }

These two functions are in the Laravel controller.

The code line of errp is: $listacontatos = getarrcontatos();

  • Are in the same controller?

  • Yes, they’re in the same controller

2 answers

3


As you are referencing a function within the same class that was instantiated it is necessary to use $this in the call to the method, so your code of the function you receive has to stay this way:

public function store(Request $request){
    $input = $request->all();
    $obscontatos = $request->input('obscontatos');
    $result = count($obscontatos);

    for ($i = 0; $i < $result ; $i++) {

        // O método é referenciado por $this e o parâmetro $request é enviado
        $listacontatos = $this->getarrcontatos($request);

        $contatoarray = array('idContato'=>$listacontatos[1],'ccContato'=>$listacontatos[2], 'idObsContato'=>$listacontatos[0]);

        DB::table('contatoObsCc')->insert($contatoarray);

    }
}

For more information about using $this take a look at the answer of the following question:

When to use self vs $this in PHP?

  • I did so, but the $list contacts variable is empty.

  • Use in the store method before any instruction the Log::info($request); directive to record the output in the log file and have an idea of what is being sent to the method, I believe it is not bringing the 'value' key and therefore the getarrcontacts method is returning empty.

1

Missing put the $this

Put it like this:

 $listacontatos = $this->getarrcontatos();

Browser other questions tagged

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