Redirect to a Specific Tab in Laravel

When using the redirect() and back() function in Laravel, my only problem has been re-directing back to the same Tab the user was on when making a request. Not re-directing back can be a pain for users as they have to navigate to the same tab they were working on.

Here is how to get it working using Laravel’s withInput function and Jquery.

In your controller method, add on withInput() and add the tab id you would like to redirect back to as the arrays value for the key of tab. Make sure it is the same in your tab navigation as on your tab pane.

My tab navigation:
<li><a href="#Galleries" data-toggle="tab"><i class="fa fa-camera" aria-hidden="true"></i> Galleries</a></li>
My tab pane:
<div class="tab-pane" id="Galleries">

As such, ive added ‘Galleries’.

//before
return back();
//after
return back()->withInput(['tab'=>'Galleries']);

Now on your page make sure you have pulled in Jquery (which you would have likely done for your tab functionality.)

Now add a new script tag and add this Jquery code that is going to be run when the page is loaded.

The {{ old(‘tab’ }} is blade syntax and is used to access past pages variables passed through the withInput function.

<script>
 //redirect to specific tab
 $(document).ready(function () {
 $('#tabMenu a[href="#{{ old('tab') }}"]').tab('show')
 });
</script>

To get this to work, make sure you add the id of tabMenu to the menu of your tab component.

Before:

<ul class="nav nav-stacked nav-pills">

After:

<ul class="nav nav-stacked nav-pills" id="tabMenu">

Now whenever you want to redirect back to a specific tab page add ->withInput([‘tab’ => ‘tabPageID’]) and you are good to go!

Additionally, we have learned to pass input from past pages when redirecting which can be very useful when we have forms split over pages or want to keep values after server-side validation failing. So feel free to keep adding keys and information to that array in withInput!