Shankar Thiyagaraajan
Shankar Thiyagaraajan

Reputation: 1795

How could i keep my $_GET params on laravel Redirect?

I try to redirect by using,

  return redirect('/customer/' . $cust_id)->with('page',2);

My Route is,

 /customer/{id}

In Customer page, i use pagination.

So i need to redirect to the same page as it comes.

But how could i pass my get param with "redirect()"

Actual URL,

 http://domain.com/customer/2?page=3   // page=>3

I need to send back the control to the same page.

Is there any solution ?

Or Is it correct way to approach ?

Upvotes: 1

Views: 3369

Answers (4)

Alexander Taubenkorb
Alexander Taubenkorb

Reputation: 3289

To do a redirect with all the current get parameters you could just use:

Assuming you are eg on page /customer/1?page=3

$get = count($_GET) ? ('?' . http_build_query($_GET)) : ''; // Taken from @steve
$cust_id = 2
return redirect()->to('/customer/' . $cust_id . $get);
// will redirect you to /customer/2?page=3

If you have a named route like

Route::get('customer/{cust_id}', [CustomerController::class, 'getCustomer'])->name('customer.show');

it is even easier:

return redirect()
    ->route(
       'customer.show',
       ['cust_id' => $cust_id] + $_GET
);
// will redirect you to /customer/$cust_id?page=3

The ->with() ist just for flashing variables. So those persist on the first view of the page. If you refresh this page, this session data is gone.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can get parameters with request()

$page = request->has('page') ? '?page='.request()->page : '';

return redirect('/customer/'.$cust_id.$page);

But if you need to redirect back to the previous page, use this:

return redirect()->back();

Upvotes: 1

Steve
Steve

Reputation: 1963

The native PHP function http_build_query() could be handly if you've got several GET variables that may be differnet for each re-direct.

// check for GET variables and build query string
$get = count($_GET) ? ('?' . http_build_query($_GET)) : '';

// redirect
return redirect('/customer/'.$cust_id.$get));

I don't use Laravel so there may be better ways of doing this but it seems like a clean solution anyway.

Upvotes: 4

Robin Dirksen
Robin Dirksen

Reputation: 3422

You should check if it's set, otherwise not redirect using the item.

Your code will be:

return redirect()->back();

Or with notification you could do:

return redirect()->back()->with('message', 'This is my message!');

Upvotes: 1

Related Questions