All About Laravel Redirect Methods

Hello artisans, today I’ll talk different usage of Laravel redirect function. Here, we can learn how we can redirect a user to route or a page or an action with or without data. So, let’s see how we can use it in our application.

Note: Tested on Laravel 8.67.

Table of Contents

  1. Redirect to URL
  2. Redirect to Route
  3. Redirect back
  4. Redirect to Controller action

Redirect to URL

Here we will start a basic method called redirect(), it accepts an parameter as URL. If we keep empty the it will redirect us to homepage of our application. Method is looks like below

return redirect(''); //take us to the homepage
return redirect('welcome'); // take us to the welcome page

Redirect to Route

Similarly you can redirect a user to a route using redirect()->route() method, where route() method accepts an parameter as route name. Method is looks like below

return redirect()->route('home'); //take us to home route

We can also pass any variable with routes like we have a post and for view we need to pass id of this post and we have a route like below

Route::get('post-view/{id}',[\App\Http\Controllers\PostController::class,'view'])->name('posts.view');

So, we use our method like below for above route

return redirect()->route('posts.view',$id); //take us to post view page

We can also pass an array like below if we need multiple parameter.

return redirect()->route('posts.view',['id' => $id,'slug' => $slug]); //take us to route page

Redirect Back

We can also redirect()->back() method by which we can redirect user to the previous page

return redirect()->back(); //redirect user to previous page

We can also use with() method which uses to flash a session variable and later we can use in a view like below

return redirect()->back()->with('success' , 'Post Saved Successfully');

{{--and in a blade you can use like these--}}
@if (session()->has('success'))
{{--    do your logic here--}}
@endif

you can also pass an array to the with() method.

$data = [
            'post' => $post,
            'category' => $post->category,
        ];
        return redirect()->back()->with($data);

Redirect to Controller Action

You can also redirect to a a controller action just like other method you have to use action() method.

return redirect()->action('PostController@index');

You can also pass a parameter method you have to use action() method.

return redirect()->action('PostController@edit', ['id' => $post->id]);

That’s all for today. Thanks for reading.