How to do a simple redirect in laravel?

Member

by dedrick , in category: PHP Frameworks , 5 months ago

How to do a simple redirect in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 5 months ago

@dedrick 

To do a simple redirect in Laravel, you can use the redirect() function, which is a helper function provided by Laravel.


Here is an example of how to do a simple redirect:

  1. In your controller method, you can use the redirect() function and pass the URL you want to redirect to as an argument:
1
2
3
4
public function redirectToPage()
{
    return redirect('/newpage');
}


  1. You can also use named routes for the redirect. To define a named route, you can use the name() method when defining your routes in the web.php file:
1
Route::get('/newpage', 'NewPageController@index')->name('newpage');


Then, in your controller method, you can use the route() function to redirect to the named route:

1
2
3
4
public function redirectToPage()
{
    return redirect()->route('newpage');
}


  1. Additionally, you can also redirect back to the previous page by using the back() method:
1
2
3
4
public function redirectToPreviousPage()
{
    return redirect()->back();
}


These are some simple examples of how to do a redirect in Laravel. You can customize the redirects further by adding other options, such as redirecting with data or specifying a status code.