A simple Laravel backend API with authentication using Laravel Sanctum and PostgreSQL.
- User registration
- User login/logout
- Protected routes with token authentication
- PostgreSQL database support
- CORS enabled for frontend integration
-
Install dependencies:
composer install
-
Configure environment:
- Update
.env
file with your PostgreSQL credentials - Set
DB_CONNECTION=pgsql
- Set
DB_HOST
,DB_PORT
,DB_DATABASE
,DB_USERNAME
,DB_PASSWORD
- Update
-
Run migrations:
php artisan migrate
-
Start the server:
php artisan serve
- POST
/api/register
- Body:
{ "name": "John Doe", "email": "john@example.com", "password": "password123", "password_confirmation": "password123" }
- Response:
{ "success": true, "message": "User registered successfully", "data": { "user": { "id": 1, "name": "John Doe", "email": "john@example.com", "created_at": "2023-01-01T00:00:00.000000Z", "updated_at": "2023-01-01T00:00:00.000000Z" }, "token": "1|abc123...", "token_type": "Bearer" } }
- POST
/api/login
- Body:
{ "email": "john@example.com", "password": "password123" }
- Response:
{ "success": true, "message": "Login successful", "data": { "user": { "id": 1, "name": "John Doe", "email": "john@example.com", "created_at": "2023-01-01T00:00:00.000000Z", "updated_at": "2023-01-01T00:00:00.000000Z" }, "token": "1|abc123...", "token_type": "Bearer" } }
- GET
/api/me
- Headers:
Authorization: Bearer {token}
- Response:
{ "success": true, "data": { "user": { "id": 1, "name": "John Doe", "email": "john@example.com", "created_at": "2023-01-01T00:00:00.000000Z", "updated_at": "2023-01-01T00:00:00.000000Z" } } }
- POST
/api/logout
- Headers:
Authorization: Bearer {token}
- Response:
{ "success": true, "message": "Logged out successfully" }
All endpoints return consistent error responses:
{
"success": false,
"message": "Error message",
"errors": {
"field": ["Validation error message"]
}
}
curl -X POST http://localhost:8000/api/register \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"password_confirmation": "password123"
}'
curl -X POST http://localhost:8000/api/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'
curl -X GET http://localhost:8000/api/me \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
curl -X POST http://localhost:8000/api/logout \
-H "Authorization: Bearer YOUR_TOKEN_HERE"