0

Disclaimer: There are already some solutions in other questions which are not at all working for me. That's why I'm writing this question. I checked solutions here... StackOverflow link

I'm getting this error... I'm getting this error...

I know why its happening: It is expecting POST request but I'm offering a GET request which ruins the game. But, what I want is to show an error message when GET request is made at /api/register

What I did to stop this: AuthController@register

public function register(Request $request)
{

    $method = $request->method();

    if ($method != 'POST'){
        return response()->json(['status' => 'error', 'message' => 'Method not Allowed.'], 405);
    }

    try{
        $user_registered = User::create([
            'fname' => $request->fname,
            'lname' => $request->lname,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'verificationToken' => str_random(100),
            'status' => 'STARTER',
            'api_token' => str_random(100)
        ]);

        $user = User::find($user_registered->id);
    } catch(\Exception $e){
        return response()->json(['status' => 'error', 'message' => 'User cannot be registered due to illegal or incomplete entry.'], 401);
    }

    return response()->json(['status' => 'success', 'user' => $user], 200);    

}

So you see I'm using an if statement to check what method is used. But its still not working.

Here's my routes/api.php file:

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

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

Please help me with this. Thanks in advance.

Kumar Abhirup
  • 197
  • 4
  • 16

2 Answers2

3

Did you try to add a new route instead?

Route::get('/register', function () {
   return response()->json(['status' => 'error', 'message' => 'Method not Allowed.'], 405);
});
B-Noid
  • 126
  • 4
2

Use Laravel any route method which accepts all HTTP requests, here is you code looks like

Route::any('/register', 'AuthController@register');

Hope it helps.

Faraz Irfan
  • 1,306
  • 3
  • 10
  • 17