DEV Community

Sanz
Sanz

Posted on

Different Ways to Redirect User

redirect() is one of the most used and popular helper function. This function redirects users to different URLs of the website. By using this method, we can redirect the user to pages with or without data.
Redirect to different URL

This is the most and simplest form in which the redirect method is used. We can redirect a user to the homepage by simply using the method below:

return redirect('/');
Enter fullscreen mode Exit fullscreen mode

Users can also pass parameters inside the redirect method. The parameters given in the method will be added to the URL of the base application.

return redirect('contact');
Enter fullscreen mode Exit fullscreen mode

Likewise, users can also pass more parameters:

return redirect('user/profile');
Enter fullscreen mode Exit fullscreen mode

back() in Laravel

If the user wants to perform some sort of tasks and redirect back to the same page then the user can use back(). This method is also really helpful.

return redirect()->back();
Enter fullscreen mode Exit fullscreen mode

Redirect to Route

Users can also name the routes in the application for consistency. Some users call named routes instead of using URLs. Let’s see an example to make this concept clear.

return redirect()->route('profile.index');
Enter fullscreen mode Exit fullscreen mode

We can also pass the second parameter in route() in the form of an array. Let's see an example of a parameterized route.

Route::get('post/{id}', 'PostController@edit')-name('post.edit');
Enter fullscreen mode Exit fullscreen mode

We can write the above above in simpler form which is here below:

return redirect()->route('post.edit', ['id' => $post->id]);
Enter fullscreen mode Exit fullscreen mode

Read the details of the post in https://laravelproject.com/different-ways-to-redirect-user/.

Top comments (2)

Collapse
 
bdelespierre profile image
Benjamin Delespierre • Edited

You can also flash session data using with like this:

return redirect('dashboard')->with('status', 'Profile updated!');

Meanwhile, in the view:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

Read more here: laravel.com/docs/7.x/responses#red...

Collapse
 
viniciusrio profile image
Vinicius Rio

Thanks, man. Simple and useful