We're working API making here
- Use sqlite, so
.env
config will be for database be like
DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
-
And in 📂database folder there have a
database.sqlite
file for database, and for database console we use SQLite browser app for windows -
As we make API, so our route file for API is
route > api.php
-
We use
postman
for API test
- We make a API function in
routes > api.php
file. which return a string
Route::get('/products', function(){
return 'products';
});
- And in Postman app we fetch or get this API and return string
http://127.0.0.1:8000/api/products
- Create Model for product with migration
php artisan make:model Product --migration
- At our product migration file (database > migrations > Products Table) we add column values
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->string('description')->nullable();
$table->decimal('price', 5, 2);
$table->timestamps();
});
}
- The make migrate
php artisan migrate
- Create a post route
- Create a Controller
php artisan make:controller ProductController --api
- We create
- product controller
index, store, show, update, destroy, search
function - Products routes methods
- Product Model
protected $fillable
objects - migration tables
- product controller
- By creating these we can make available api for
- show products
http://127.0.0.1:8000/api/products
- Store products
http://127.0.0.1:8000/api/products
- Update single products
http://127.0.0.1:8000/api/products/1
- Delete single products
http://127.0.0.1:8000/api/products/1
- Search products
http://127.0.0.1:8000/api/products/search/name
- show products
- On the latest version of Laravel, sanctum is pre-installed
- For authenticate a SPA, it should add Sanctum's middleware to api middleware group in
app/Http/Kernel.php
file, in latest version of Laravel it is already added, just uncomment the file.
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
- To begin issuing tokens for users,
User model
should use theLaravel\Sanctum\HasApiTokens
trait inapp/models/user.php
- Create route middleware for protected auth route, from
Route::get('/products/search/{name}', [ProductController::class, 'search']);
to
Route::group(['middleware' => ['auth:sanctum']], function(){
Route::get('/products/search/{name}', [ProductController::class, 'search']);
});
- So we have now public and protected routes
// Public get Routes, show & search products and id
Route::get('/products', [ProductController::class, 'index']);
Route::get('/products/{id}', [ProductController::class, 'show']);
Route::get('/products/search/{name}', [ProductController::class, 'search']);
// Route for search a product name with Laravel Sanctum protected route auth
Route::group(['middleware' => ['auth:sanctum']], function(){
Route::post('/products', [ProductController::class, 'store']);
Route::put('/products/{id}', [ProductController::class, 'update']);
Route::delete('/products/{id}', [ProductController::class, 'destroy']);
});
- Create a Auth controller,
php artisan make:controller AuthController
- Then we can register auth controller
// Register auth Controller
Route::get('/register', [AuthController::class, 'register']);
-
If controller and route is perfect then we can register a user by Postman and get response like this . If error shown, then also check Postman header parameter
-
After that, we can now register a product by our authenticate user, but before that we need to authorize the user token in postman
-
Now create a logout AuthController function & Protected auth route
public function logout(Request $request)
{
auth()->user()->tokens()->delete();
return [
'message' => 'Logged out'
];
}
Route::post('/logout', [AuthController::class, 'logout']);
- If Authorization token, header & Body is perfectly give then we get logout response
- Now create a login AuthController function & Public auth route
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]);
//Check email
$user = User::where('email', $fields['email'])->first();
// Check password
if(!$user || !Hash::check($fields['password'], $user->password))
{
return response([
'message' => "Unauthorize Creds"
]);
}
$token = $user->createToken('myapptoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
Route::post('/login', [AuthController::class, 'login']);
- Now we able to create login by right credentials
Finally we're able to create a Products API with Sanctum which provide API endpoints of
- Get Products
- Create Products by Authorize User
- Update Products by Authorize User
- Delete Products by Authorize User
- Search Products
- Register a user
- Login user
- Logout user