Laravel redirects in a controller

2

I have a controller that receives a call for post , with some data in the request ( $request ). I need that controller to do a calculation and then redirect to another controller, sending the same data that he received in the body of the request. I have tried the following:

public function destino1(Request $request)
{
    dump ("DESTINO 1: ", $request);
    return redirect()->route('operatorDestino2')->with($request);
}

public function destino2(Request $request)
{
    dd ("DESTINO 2: ", $request);
}

I've also tried the withInput() method, instead of with() .

However, this does not work. What I get is an exception of type MethodNotAllowedHttpException , which gives me to understand that the redirect() is not understood with the method post , but redirects only by get . That makes it impossible to pass the body of the petition.

Is there an alternative in Laravel to jump from one controller to another by passing the original $request received by the first controller?

    
asked by Chefito 22.12.2018 в 16:42
source

1 answer

1

Let's say in simple terms that by design conventions it is wrong to call a controller from another controller, so you should look for a solution that allows both controllers to communicate without calling each other.

Taking into account that we do not have enough information about what the different controllers are doing, I propose a generic solution that allows to abstract the handling of the information to avoid the error of calling one or another controller.

The option is to create a service layer, to which the information can be passed from the first controller and which will finally be the one that processes all the information and performs the necessary calculations, etc.

class FirstController extends Controller 
{
    // el servicio puede ser inyectado según la necesidad o llamado directamente

    public function getData(Request $request)
    {
        // recibir información y pasarla al servicio
        MyService::processData($request->all());
    }
}

Service:

class MyService
{
    public function processData($data)
    {
        // hacer cálculos
        // determinar qué hacer según los valores recibidos o cálculos realizados
        // llamar otros métodos del servicio, o procesar toda la información en este método
    }

    // de ser necesario, los otros controladores pueden utilizar este servicio también para almacenar o buscar información
}
    
answered by 22.12.2018 / 17:05
source