Laravel Redirect to URL using redirect() helper Example

Jan 20, 2023 . Admin



Hi dev,

I'll demonstrate in this article how to direct people from one website to another using the controller technique. In controllers, we often utilise the helper function redirect for user redirection ().

In Laravel 5, Laravel 6, Laravel 7, Laravel 8, and Laravel 9, we can easily use the redirect() helper. redirection supplied by Laravel version (). In Laravel, there are numerous ways to perform URL redirection. I'm going to show you how to redirect a URL with parameters step-by-step in this post.

Redirect to URL

you can simply redirect given URL, bellow example i simple redirect "mywebtuts/tags" URL.

Route
Route::get('mywebtuts/tags', 'HomeController@tags');	
Controller Method:
public function home()
{
    return redirect('mywebtuts/tags');
}	
Redirect back to previous page

In this example, we can redirect back to our previous page URL, so you can do it both way:

public function home()
{
    return back();
}
OR
public function home2()
{
    return redirect()->back();
}	
Redirect to Named Routes

If you declare route with name and you want to redirect route from controller method then you can simply do it.

Route:
Route::get('mywebtuts/tags', array('as'=> 'mywebtuts.tags', 'uses' => 'HomeController@tags'));	
Controller Method:
public function home()
{
    return redirect()->route('mywebtuts.tags');
}	
Redirect to Named Routes with parameters

If you declare route with name and also parameters and you want to redirect route from controller method then you can do it by following example.

Route:
Route::get('mywebtuts/tag/{id}', array('as'=> 'mywebtuts.tag', 'uses' => 'HomeController@tags'));	
Controller Method:
public function home()
{
    return redirect()->route('mywebtuts.tag',['id'=>17]);
}	
Redirect to Controller Action

we can also redirect controller method using action of redirect() helper as you can see bellow example:

public function home()
{
    return redirect()->action('App\Http\Controllers\HomeController@home');
}	
Redirect to Controller Action With Parameters

we can also redirect controller method using action with parameters of redirect() helper as you can see bellow example:

public function home()
{
    return redirect()->action('App\Http\Controllers\HomeController@home',['id'=>17]);
}	
Redirect with Flashed Session Data

we can also pass flashed session message while redirect with routes or url in controller method as you can see bellow example.

public function home()
{
    return redirect('home')->with('message', 'Welcome to mywebtuts Tutorials!');
}	

You can simply redirect above ways to URL from controller method.

Maybe it can help you....

#Laravel