TheQuietOne
TheQuietOne

Reputation: 41

Form redirecting to wrong controller method upon submitting Laravel 8

I have created a user settings page with an input field to allow the connected user to change their username. However, when changing the name in the input field and submitting the form, the page refreshes with the old username. I figured out that the request was going to my show method instead of the update method. The weird part is that if I remove the route linked to the update method (PUT), I get the following error.

The PUT method is not supported for this route. Supported methods: GET, HEAD.

But if I leave it, the request takes the show route (GET) instead.

Form

    <div class="row">
        <div class="col-sm-6">
            <form method="POST" action="/user/{{ $user->id }}">
                @csrf
                @method('PUT')
                <input type="text" name="name" id="name" value="{{ $user->name }}"/>

                <!-- Sends to show instead of update ! -->
                <input type="submit" class="btn btn-custom" value="Save name">
            </form>
        </div>
    </div>

web.php

Route::get('/user/{user}', [UserController::class, 'show']);
Route::put('/user/{user}', [UserController::class, 'update']);

UserController.php

class UserController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function show(User $user)
    {

        if (!$this->isLoggedIn($user->id)) {
            return back()->withInput();
        }

        return view('users.profile', ['user' => $user]);
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        // dump($user);die; (This doesn't work, I'm only going through show())
        if (!$this->isLoggedIn($user->id)) {
            return back()->withInput();
        }

        $user->name = $request->get('name');

        $user->save();

        return view('users.show', ['user' => $user]);
    }

    public function isLoggedIn($id)
    {
        if ($id == Auth::user()->id) {
            return true;
        }

        return false;
    }
}

Upvotes: 1

Views: 583

Answers (1)

TheQuietOne
TheQuietOne

Reputation: 41

Actually found the issue :

It was coming from the validation rules in my request. The request was expecting a name, email and password while I was sending a name alone for update.

Changed the rules for update and it works correctly now.

Cheers

Upvotes: 1

Related Questions