Add the following code in

Transform business strategies with advanced india database management solutions.
Post Reply
poxoja9630
Posts: 8
Joined: Sun Dec 22, 2024 5:35 am

Add the following code in

Post by poxoja9630 »

php file : PHP Copy the code // routes/api.php Route::post('/login', [AuthController::class, 'login']); Then add the login() method in AuthController: PHP Copy the code // app/Http/Controllers/AuthController.php use App\Models\User; use Illuminate\Support\Facades\Auth; public function login(Request $request) { if (!Auth::attempt($request->only('email', 'password'))) { return response()->json([ 'message' => 'Invalid login details' ], 401); } $user = User::where('email', $request['email'])->firstOrFail(); $token = $user->createToken('auth_token')->plainTextToken; return response()->json([ 'access_token' => $token, 'token_type' => 'Bearer', ]); } In the above code, we check if the provided email address and password match those in the table users, and then create a new personal access token for the user. Let's add the last functionality, which is used to retrieve the currently authenticated user account.

Add the following code in the routes/api.php file : PHP Copy the telegram philippines girl code // routes/api.php Route::post('/me', [AuthController::class, 'me']); Then add this code to the AuthController: PHP Copy the code // app/Http/Controllers/AuthController.php public function me(Request $request) { return $request->user(); } This code is pretty simple. We just return the currently authenticated user account. Restricting endpoint to authenticated user accounts only As you may have guessed, the endpoint /me should be accessible only to authenticated user accounts. Luckily for us, this is possible thanks to Authenticated Protection sanctum. So we will update the path as follows: PHP Copy the code // routes/api.

Image

php Route::post('/me', [AuthController::class, 'me'])->middleware('auth:sanctum'); This ensures that requests sent to this endpoint contain a valid API token in their header. Before testing the API, let's uncomment the line below in app/Providers/RouteServiceProvider.php : PHP Copy the code // app/Providers/RouteServiceProvider.php protected $namespace = 'App\\Http\\Controllers'; API Testing It's time to test what we've built. I'll show you instructions using Insomnia , but you're free to use any HTTP client you feel comfortable with. First, make sure the application is running: Bash Copy the code php artisan serve The application should be running on and we can access the API on
Post Reply