To create a Laravel API with Sanctum, you can follow these steps:
Install Laravel Sanctum:
Publish the Sanctum configuration and migration files:
Run the Sanctum migrations:
Add the HasApiTokens trait to your User model:
Register the Sanctum middleware in your Kernel class:
Generate a new API token for your authenticated user:
Use the generated API token to authenticate your API requests:
You can now create your API routes and controllers as usual. To protect a route with Sanctum, you can use the auth:sanctum middleware:
CRUD EXAMPLE
Next, let's create a Product model and migration file to store our product data. Run the following commands to create them:
This will create a Product.php model file and a migration file for the products table.
In the migration file, add the following code to define the columns for the products table:
Next, run the migration to create the products table:
Now, let's create a ProductController to handle the CRUD operations. Run the following command to generate a new controller:
This will create a new ProductController.php file in the app/Http/Controllers folder with boilerplate code for a RESTful API.
Add the following code to the ProductController to define the CRUD methods:
Next, let's protect our API routes with Sanctum. In the routes/api.php file, add the following code to define the routes and apply the auth:sanctum middleware:
Now, to test our API, we can use tools like curl or Postman to send HTTP requests to the API endpoints.
For example, to create a new product, we can send a POST request to http://localhost:8000/api/products with a JSON payload:
To retrieve all products, we can send a GET request to http://localhost:8000/api/products.
To update a product, we can send a PUT request to http://localhost:8000/api/products/{product_id} with a JSON payload:
To delete a product, we can send a DELETE request to http://localhost:8000/api/products/{product_id}.
I hope this helps you get started with creating a Laravel API with Sanctum.
No comments:
Post a Comment