Best laravel framework open-source packages.

Laravel Sanctum

Laravel API Development
Updated 2 months ago

Create Products API

We're working API making here

  1. Use sqlite, so .env config will be for database be like
DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
  1. And in 📂database folder there have a database.sqlite file for database, and for database console we use SQLite browser app for windows

  2. As we make API, so our route file for API is route > api.php

  3. We use postman for API test

Test Initial API

  1. We make a API function in routes > api.php file. which return a string
Route::get('/products', function(){
    return 'products';
});
  1. And in Postman app we fetch or get this API and return string

http://127.0.0.1:8000/api/products

Make API for Products

  1. Create Model for product with migration php artisan make:model Product --migration
  2. 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();
    });
}
  1. The make migrate php artisan migrate
  2. Create a post route
  3. Create a Controller php artisan make:controller ProductController --api
  4. We create
    • product controller index, store, show, update, destroy, search function
    • Products routes methods
    • Product Model protected $fillable objects
    • migration tables
  5. 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

Laravel Sanctum

  1. On the latest version of Laravel, sanctum is pre-installed
  2. 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,
],
  1. To begin issuing tokens for users, User model should use the Laravel\Sanctum\HasApiTokens trait in app/models/user.php
  2. 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']);
});
  1. 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']);
});
  1. Create a Auth controller, php artisan make:controller AuthController
  2. Then we can register auth controller
// Register auth Controller
Route::get('/register', [AuthController::class, 'register']);
  1. If controller and route is perfect then we can register a user by Postman and get response like this register route. If error shown, then also check Postman header parameter header parameter

  2. Now we can register a user, and get a token register user

  3. After that, we can now register a product by our authenticate user, but before that we need to authorize the user token in postman

    • authorize
    • Register a product
  4. 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']);
  1. If Authorization token, header & Body is perfectly give then we get logout response

logout

  1. 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']);
  1. Now we able to create login by right credentials

login

Finally

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

Postman API Credentials

Here is all of API Credentials

Tags sanctum