@leon012 Is there any particular reason to pass the query parameter for POST route?
// Route::post('login', [RegisterController::class, 'login']);
http://localhost:8000/api/[email protected]&password=password
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to create an api for user , can register and login. It work until now, so i can create user account and can login but i canot get token. My response on postman is this
//this is reoute
POST:http://localhost:8000/api/login?email=api-user2@gmail.com&password=password
"success": true,
"data": {
"token": {
"name": "passport_token",
"abilities": [
"*"
],
"tokenable_id": 10,
"tokenable_type": "App\Models\User",
"updated_at": "2023-01-10T09:18:20.000000Z",
"created_at": "2023-01-10T09:18:20.000000Z",
"id": 13
},
"name": "api-user2"
},
"message": "User login successfully."
}
//API royte
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
Route::middleware('auth:api')->group( function() {
});
//RegisterControiller
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Validator;
class RegisterController extends BaseController
{
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8'],
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('passport_token')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User register successfully.');
}
/**
* Login api
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('passport_token')-> accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
@tisuchi I found the solution. The problem was on the user modal i was using Sanctum
use Laravel\Sanctum\HasApiTokens; replace with
use Laravel\Passport\HasApiTokens;
Please or to participate in this conversation.