Handling Redirects In Laravel

Laravel, like every other framework, supports HTTP redirects. Here, we will be seeing how to implement redirects using various approaches in Laravel.

Redirecting to specific path

To redirect to a specific path, we use the global redirect helper:

Route::get('/home', function () {
    return redirect('/dashboard');
});

Redirecting to named route

We can also redirect to routes using their names instead of the path.

Take a look below to see how to do that:

a. with parameters:

return redirect()->route('dashboard');

b. without parameters:

return redirect()->route('dashboard', ['username' => 'John']);

Redirecting to previous page

We could also redirect to a previous location. To achieve this, we leverage the global back function helper:

return back();

Redirecting to controller actions

We could also generate redirect to specific actions in controllers. To achieve this, we pass the controller and action name to the action method:

a. with parameters:

return redirect()->action([ProfileController::class, 'index'], ['id' => 2]);

b. without parameters:

return redirect()->action([ProfileController::class, 'index']);

Thanks for reading!