Roderik
Roderik

Reputation: 337

Redirect to route without get params with Laravel

I have some legacy urls with get params that I want to redirect to the route without these get parameters.

In my web.php I have:

Route::get('/', ['as' => 'welcome', 'uses' => 'PageController@welcome']);

URLs like http://example.com/?page_id=5 should redirect (302) to http://example.com/.

In the controller I tried the following:

public function welcome(Request $request)
{
    if($request->has('page_id')) {

        redirect()->to('welcome', 302);
    }

    return view('welcome');
}

It reaches the redirect but the the url still has the ?page_id=5 in it. Something like:

redirect()->to('welcome', 302)->with('page_id', null);

Made no difference as well. What is the best way in Laravel 5.3 to redirect a page with parameters after the ? to one without parameters?

Upvotes: 4

Views: 4539

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You should use return in front of the redirect() method to make it work:

public function welcome(Request $request)
{
    if($request->has('page_id')) {

        return redirect()->route('welcome');
    }

    return view('welcome');
}

Hope this helps!

Upvotes: 6

Related Questions