Home Laravel How To Redirect to Route from Controller In Laravel ?

How To Redirect to Route from Controller In Laravel ?

by Shahriar Sagor

Hello Dev, Today now in this post i will show you How To Redirect to Route from Controller In Laravel ? From here you will know How To Redirect to Route from Controller In Laravel ? In this post i will give you a very simple example of how to redirect t route in laravel controller. So Let’s get started with the how to return route in laravel.

 Here i will be use redirect(), route() and to_route() functions for redirect to route. We need to pass the route name as an argument.

You can see in the below example code:

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");
    }
}

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like