20-Jan-2023
.
Admin
Hi dev,
In this article, I'll show you how to use the controller technique to redirect users from one website to another. For user redirection in controllers, we typically utilise the helper function redirect().
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 "nicesnippets/tags" URL.
Route
Route::get('nicesnippets/tags', 'HomeController@tags');
Controller Method:
public function home()
{
return redirect('nicesnippets/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('nicesnippets/tags', array('as'=> 'nicesnippets.tags', 'uses' => 'HomeController@tags'));
Controller Method:
public function home()
{
return redirect()->route('nicesnippets.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('nicesnippets/tag/{id}', array('as'=> 'nicesnippets.tag', 'uses' => 'HomeController@tags'));
Controller Method:
public function home()
{
return redirect()->route('nicesnippets.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 Nicesnippets Tutorials!');
}
You can simply redirect above ways to URL from controller method.
Maybe it can help you....
#Laravel