Laravel Framework
2025-01-26 22:12:36
Published By
KhalequzzamanHandling Laravel Redirects with Fallback
In Laravel, `return back()` redirects the user to the previous page. However, if there is no previous URL (e.g., when the route is accessed directly), it can cause issues. You can add a fallback to redirect the user to a default page, such as `/`.
Example Code:
Route::get('/optimize', function () {
Artisan::call('optimize:clear');
// Redirect to previous URL or home page if none exists
return back()->getTargetUrl() !== url()->previous()
? back()
: redirect('/');
})->name('optimize');