Page 1 of 1

Before we can start using

Posted: Sun Dec 22, 2024 9:08 am
by poxoja9630
Before we can start using Laravel Sanctum to create tokens for users, we finally need to make sure that the model User uses the feature HasApiTokens. Open the app/Models/User.php file and add the following changes to it: PHP Copy the code // app/Models/User.php use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; } Building the API For simplicity, the API will only have three endpoints. The first allows users to register an account, while the second allows them to login/authenticate. The third retrieves the currently authenticated user account. Let's start by creating an account.

In your terminal, create the controller responsible for authentication telegram philippines girl by running the following Artisan command: Bash Copy the code php artisan make:controller AuthController A new file, named AuthController.php , will be generated in the app/Http/Controllers folder . Now open the routes/api.php file to create the route responsible for registering a user account: PHP Copy the code // routes/api.php use App\Http\Controllers\AuthController; Route::post('/register', [AuthController::class, 'register']); Open it AuthController and add the following piece of code to create the method to register a new user: PHP Copy the code // app/Http/Controllers/AuthController.php use Illuminate\Support\Facades\Hash; public function register(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8', ]); $user = User::create([ 'name' => $validatedData['name'], 'email' => $validatedData['email'], 'password' => Hash::make($validatedData['password']), ]); $token = $user->createToken('auth_token')->plainTextToken; return response()->json([ 'access_token' => $token, 'token_type' => 'Bearer', ]); } First, we validate the incoming request to ensure that all required variables are present.


Image

Then, we persist the provided details within the database. Once a user account is created, we generate a new personal access token for it using the method createToken() , and we call it auth_token . Since createToken() (create token) returns an instance of Laravel\Sanctum\NewAccessToken, we call the property plainTextToken on the instance to access the plain text value of the token. Finally, we return a JSON response containing the generated token along with the token type. Next let's add the implementation to allow users to log in again. Add the code below to the routes/api.