Search code examples
phplaravelrestpostlaravel-passport

Laravel API: The POST method is not supported for this route. Supported methods: GET, HEAD


I am sending a post request to http://localhost/projects/webdevlist/public/api/register and getting the 405 error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.

routes\api.php:

<?php

use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/register', 'Api\AuthController@register');

Api\AuthController.php:

<?php

namespace App\Http\Controllers\Api;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:55',
            'email' => 'required|email',
            'password' => 'required|confirmed'
        ]);

        $user = User::create($validatedData);

        $accessToken = $user->createToken('token')->accessToken;

        return response(['user' => $user, 'access_token' => $accessToken]);
    }
}

If I remove the form validation then I can do post requests just fine and return a result in postman like this.

<?php

namespace App\Http\Controllers\Api;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        return response()->json([
            $request->name,
            $request->email,
            $request->password,
        ]);
    }
}

But something is wrong with my validation. Why does the validation cause me to no longer be able to accept POST requests?

Here is my POST request: enter image description here


Solution

  • The problem with your validation is the password field.

    Your rule say that it need to be required and confirmed, but confirmed against which field?

    You need to add a field with name password_confirmation your view, if not added yet.

     <input type="password" name="password_confirmation" />
    

    And then add a new rule for password_confirmation field:

    $validatedData = $request->validate([
        'name' => 'required|max:55',
        'email' => 'required|email',
        'password' => 'required|confirmed',
        'password_confirmation' => 'required'
    ]);