Search code examples
laravelroutesreload

After editing user details, when submiting need to redirect to user page with the fresh edit details


i'm facing a simple but hard routing problem! so i'm building an app with laravel using blade. My problem is simple, when i'm editing the user details, i'm redirecting to my user page as i want but the informations are not updating! how can i do that? i tried so many things that i can't see wha't wrong anymore!

Can someone help me understand my mistakes? thanks! a french newbie :)

<button type="submit" class="btn btn-outline-success btn-block"><a href="{{redirect()->route('users.show',['id'=>$user->id])}}"></a>Valider la modification</button>


Solution

  • The href attribute of the <a> inside the <button> takes precedence over the <form>'s action attribute, therefore your update action is never called. You should perform the redirect in your route action, e.g. the controller:

    class UserController extends Controller
    {
        // other actions
    
        public function update(Request $request, $id)
        {
            $user = User::find($id);
            $user->fill($request->all()); // Do not fill unvalidated data
    
            if (!$user->save()) {
                // Handle error
    
                // Redirect to the edit form while preserving the input
                return redirect()->back()->withInput();
            }
    
            // Redirect to the 'show' page on success
            return redirect()->route('users.show', ['id' => $user->id]);
        }
    
        // more actions
    }
    

    Your form should then look similar to this:

    <form action="{{ route('user.update', ['id' => $user->id]) }}" method="POST">
        <!-- Use @method and @csrf depending on your route's HTTP verb and if you have CSRF protection enabled -->
        @method('PUT')
        @csrf
        <!-- Your form fields -->
        <button type="submit" class="btn btn-outline-success btn-block">
            Valider la modification
        </button>
    </form>