Home > Enterprise >  Laravel:: How to attach a Request instance to redirect?
Laravel:: How to attach a Request instance to redirect?

Time:08-28

I have a controller function that accepts Request instant from form through a get method, I want to redirect to this route from the controller and attach a Request to it.

Route

        Route::get('/{order_id}/return-calc', 'returnCalc')->name('return-calc');

Controller

    public function return(Request $request, $order_id)
    {
        $order = Order::with([
            'products' => fn ($q) => $q->with('thumbnail')
        ])->findOrFail($order_id);

        if ($request->method() == 'GET') {
            return view('front.orders.return_products', compact('order'));
        } elseif ($request->method() == 'DELETE') {
            $request = new Request([
                'products_ids' => $order->products->pluck('id')->toArray(),
                'quantities' => $order->products->pluck('pivot.quantity')->toArray(),
            ]);

            return redirect()->route('front.orders.return-calc', [$order_id, $request]);
        }
    }

CodePudding user response:

Passing data to the route function is for route parameters, to share data between requests you should store it in the session if it's a one time thing you can "flash" it

https://laravel.com/docs/9.x/responses#redirecting-with-flashed-session-data

Add ->with() to the response

public function return(Request $request, $order_id)
    {
        $order = Order::with([
            'products' => fn ($q) => $q->with('thumbnail')
        ])->findOrFail($order_id);

        if ($request->method() == 'GET') {
            return view('front.orders.return_products', compact('order'));
        } elseif ($request->method() == 'DELETE') {
            $request = new Request([
                'products_ids' => $order->products->pluck('id')->toArray(),
                'quantities' => $order->products->pluck('pivot.quantity')->toArray(),
            ]);

            return redirect()->route('front.orders.return-calc')->with(['order_id' => $order_id]);
        }
    }

CodePudding user response:

If you need a request instance in your blade file, you can directly use request() or Request class. But if you need data like products_ids, quantities you can pass it like this:

public function return(Request $request, $order_id)
{
    $order = Order::with([
        'products' => fn ($q) => $q->with('thumbnail')
    ])->findOrFail($order_id);

    if ($request->method() == 'GET') {
        return view('front.orders.return_products', compact('order'));
    } elseif ($request->method() == 'DELETE') {
        $data = [
            'products_ids' => $order->products->pluck('id')->toArray(),
            'quantities' => $order->products->pluck('pivot.quantity')->toArray(),
        ];

        return redirect()->route('front.orders.return-calc', [ 'order_id' => $order_id])->with('data', $data);
    }
}
  • Related