Laravel Redirect to Route from Controller Example

By Hardik Savani April 16, 2024 Category : Laravel

Hello Artisan,

This tutorial is focused on laravel redirect to route from controller. you will learn laravel redirect from route name. In this article, we will implement a how to redirect to another route in laravel. This post will give you a simple example of how to redirect route in laravel controller. Let's get started with how to return route in laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

We mostly need to redirect the route from the controller method in the laravel project. Laravel provides several ways to return redirect with route name in laravel. I will give you three ways to return a redirect to a specific route from the controller function. we will use redirect(), route() and to_route() functions for redirect to route. you need to pass the route name as an argument.

You can see below example code:

Demo Routes:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

use App\Http\Controllers\HomeController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('users', [UserController::class, 'index']);

Route::get('home', [HomeController::class, 'index'])->name("home");

Example 1: using redirect() with route()

Controller File:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request, $page = 1)

{

$users = User::get();

return redirect()->route("home");

}

}

Example 2: using to_route()

Controller File:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request, $page = 1)

{

$users = User::get();

return to_route("home");

}

}

Example 3: using redirect()

Controller File:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request, $page = 1)

{

$users = User::get();

return redirect("home");

}

}

I hope it can help you...

Tags :
Shares