Home > Mobile >  Post method not allowing data in body request Laravel 9 (postman)
Post method not allowing data in body request Laravel 9 (postman)

Time:11-04

I've created an api an it works however there is a weird behavior it doesnt allow me to send data in the body of the request. Here's my code:

api.php

Route::controller(AuthController::class)->group(function () {
    Route::post('login', 'login');
    Route::post('register', 'register');
    Route::post('logout', 'logout');
    Route::post('refresh', 'refresh');
    Route::get('me', 'me');
});

AuthController.php

class AuthController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login','register']]);
    }

    public function register(Request $request){
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = Auth::login($user);
        return response()->json([
            'status' => 'success',
            'message' => 'User created successfully',
            'user' => $user,
            'authorisation' => [
                'token' => $token,
                'type' => 'bearer',
            ]
        ]);
    }
}

if i send data like this

localhost:8000/api/register?name=odlir4&[email protected]&password=password

enter image description here

it works fine but if i send it like this

enter image description here

this doesn't work, anyone knows why this is happening? i think it should work or am i wrong?

Thank you!

CodePudding user response:

in the route register you define the POST method

api.php

Route::post('register', 'register');

in postman you send data using GET method because it passes parameter

localhost:8000/api/register?name=odlir4&[email protected]&password=password

it should be like this in Tab Body https://www.postman.com/postman/workspace/published-postman-templates/request/631643-083e46e7-53ea-87b1-8104-f8917ce58a17

CodePudding user response:

You need to get form-data in your controller using below method

public function register(){

  $datarequest = $this->input->post();

// other code

}

OR if you want to send request in json

public function register(){

  $datarequest = json_decode(file_get_contents('php://input'),true);

// other code

}
  • Related