https://dev.to/techtoolindia #make-rest-api-authentication-in-laravel-9-using-laravel-sanctum Make REST API AUTHENTICATION in LARAVEL 9 USING LARAVEL SANCTUM Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. If you are not using LARAVEL 9 you need to install LARAVEL Sanctum Otherwise you can skip the installation step.

Route::post('/auth/register', [AuthController::class, 'createUser']); Route::post('/auth/login', [AuthController::class, 'loginUser']); Now update AuthContoller with all(), [ 'name' => 'required', 'email' => 'required|email|unique:users,email', 'password' => 'required' ]); if($validateUser->fails()){ return response()->json([ 'status' => false, 'message' => 'validation error', 'errors' => $validateUser->errors()], 401); } $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password)]); return response()->json([ 'status' => true, 'message' => 'User Created Successfully', 'token' => $user->createToken("API TOKEN")->plainTextToken ], 200); } catch (\Throwable $th) { return response()->json([ 'status' => false, 'message' => $th->getMessage()], 500); }} /** * Login The User * @param Request $request * @return User */ public function loginUser(Request $request) { try { $validateUser = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required' ]); if($validateUser->fails()){ return response()->json([ 'status' => false, 'message' => 'validation error', 'errors' => $validateUser->errors()], 401); } if(!Auth::attempt($request->only(['email', 'password']))){ return response()->json([ 'status' => false, 'message' => 'Email & Password does not match with our record.', ], 401); } $user = User::where('email', $request->email)->first(); return response()->json([ 'status' => true, 'message' => 'User Logged In Successfully', 'token' => $user->createToken("API TOKEN")->plainTextToken ], 200); } catch (\Throwable $th) { return response()->json([ 'status' => false, 'message' => $th->getMessage()], 500); }} } #protect-api-with-authentication-we-need-to-use-raw-authsanctum-endraw-middleware Protect API With Authentication we need to use auth:sanctum middleware.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners