To create a Laravel API with Sanctum, you can follow these steps:
Install Laravel Sanctum:
composer require laravel/sanctum
Publish the Sanctum configuration and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Run the Sanctum migrations:
Add the HasApiTokens trait to your User model:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
Register the Sanctum middleware in your Kernel class:
protected $middlewareGroups = [
// ...
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreAuthorized::class,
],
];
Generate a new API token for your authenticated user:
$token = $user->createToken('API Token')->plainTextToken;
Use the generated API token to authenticate your API requests:
Authorization: Bearer {api_token}
You can now create your API routes and controllers as usual. To protect a route with Sanctum, you can use the auth:sanctum middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
CRUD EXAMPLE
Next, let's create a Product model and migration file to store our product data. Run the following commands to create them:
php artisan make:model Product -m
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:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
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:
php artisan make:controller ProductController --api
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:
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return response()->json($products);
}
public function store(Request $request)
{
$product = Product::create($request->all());
return response()->json($product);
}
public function show(Product $product)
{
return response()->json($product);
}
public function update(Request $request, Product $product)
{
$product->update($request->all());
return response()->json($product);
}
public function destroy(Product $product)
{
$product->delete();
return response()->json(null, 204);
}
}
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:
use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('products', ProductController::class);
});
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:
{
"name": "Product A",
"description": "This is product A",
"price": 19.99
}
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:
{
"name": "Product A (updated)",
"description": "This is product A (updated)",
"price": 29.99
}
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.