简体   繁体   中英

Return to same tab after form submit laravel 8

I have a view with multiple tabs. Each having different forms. When I submit a form from one tab, it returns to same page but primary tab. How could I get to return to same tab from which I was working.

controller

  public function updateProfile(Request $request)
   {

        $user = User::where('id', Auth::user()->id)->first();
        $user->update([
            'full_name' => $request->full_name,
            'phone'     => $request->phone,
        ]);
    }

    return redirect()->back();
 }

html form

<form  action="{{route('management.update')}}" method="POST" enctype="multipart/form- 
data">
      

This is how my tabs are:

      <ul class="nav nav-tabs mb-5" id="ex1" role="tablist">
          <li class="nav-item" role="presentation">
                <a class="nav-link active" id="ex1-tab-2" data-mdb-toggle="tab" href="#ex1- 
                   tabs-2" role="tab"
                aria-controls="ex1-tabs-2" aria-selected="false"><i class='bx bxs-user- 
                 rectangle'></i> User</a>
            </li>
            @endif
            <li class="nav-item" role="presentation">
                <a class="nav-link " id="ex1-tab-1" data-mdb-toggle="tab" href="#ex1-tabs-1" 
                  role="tab"
                    aria-controls="ex1-tabs-1" aria-selected="true"><i class='bx bx- 
                 buildings'></i> Profile</a>
            </li>
        </ul>

On the controller send the data on which tab should be set active after redirect. You can do it by sending flash session.

Session::flash('active-tab', '#ex1-tab-1'); 

Then on the view end, check if the session exists and make the tab active with the data on session.

@if(Session::has('active-tab'))
@php
    $active_tab= Session::get('active-tab');
@endphp
$(document).ready(function(){
     $(".active").removeClass("active");
     $('{{$active_tab}}').addClass("active");
})

@endif

Inside your html form add hidden input element.

<input type="hidden" name="tab" value="<the tab id>">

And in your Controller, return your route with data, and put the request tab on it.

$data =['tab' => $request->tab];

return redirect()->back()->with($data);

Lastly, in your nav link and tab pane, put a condition to check the tab value

<a class="nav-link @if (request('tab') == 'ex1-tab-2') active @endif" ..>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM