PHP code example of hitaqnia / haykal-api

1. Go to this page and download the library: Download hitaqnia/haykal-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hitaqnia / haykal-api example snippets


namespace App\Providers\Apis;

use Dedoc\Scramble\Support\Generator\SecurityScheme;
use HiTaqnia\Haykal\Api\ApiProvider;

final class PropertiesApiProvider extends ApiProvider
{
    protected function name(): string
    {
        return 'properties-api';
    }

    protected function path(): string
    {
        return 'api/properties';
    }

    protected function title(): string
    {
        return 'Properties API';
    }

    protected function description(): string
    {
        return 'Property management endpoints for the admin dashboard.';
    }

    // Optional hooks below.

    protected function version(): string
    {
        return '1.2.0';
    }

    protected function logo(): ?string
    {
        return asset('logo.png');
    }

    protected function primaryColor(): ?string
    {
        return '#4432d2';
    }

    /**
     * Security schemes to register in addition to the bearer scheme
     * (which is always installed). Typical additions are header-based
     * tenant or profile selectors.
     *
     * @return array<string, SecurityScheme>
     */
    protected function additionalSecuritySchemes(): array
    {
        return [
            'complex' => SecurityScheme::apiKey('header', 'X-Complex-Id'),
        ];
    }
}

return [
    App\Providers\AppServiceProvider::class,

    App\Providers\Apis\PropertiesApiProvider::class,
];

// routes/api.php

// routes/api/properties-api.php
use App\Apis\Properties\Controllers\CreatePropertyController;
use App\Apis\Properties\Controllers\ListPropertiesController;
use Illuminate\Support\Facades\Route;

Route::prefix('properties')
    ->middleware(['auth:sanctum', 'haykal.session.token'])
    ->group(function () {
        Route::get('/', ListPropertiesController::class);
        Route::post('/', CreatePropertyController::class);
    });

final class PropertiesApiProvider extends ApiProvider
{
    protected function name(): string        { return 'properties-api'; }
    protected function title(): string       { return 'Properties API'; }
    protected function description(): string { return 'Property management endpoints.'; }

    protected function versions(): array
    {
        return [
            'v1' => 'api/v1/properties',
            'v2' => 'api/v2/properties',
        ];
    }

    protected function version(string $versionId = self::DEFAULT_VERSION): string
    {
        return match ($versionId) {
            'v1' => '1.4.0',
            'v2' => '2.0.0',
            default => '1.0.0',
        };
    }
}

use HiTaqnia\Haykal\Api\Response\ApiResponse;

return ApiResponse::ok(message: 'Profile retrieved.', data: new UserResource($user));
return ApiResponse::created(message: 'Reservation booked.', data: $reservation);
return ApiResponse::noContent();

return ApiResponse::paginated(
    message: 'Units retrieved.',
    data: Unit::query()->paginate($request->integer('per_page', 15)),
);

return ApiResponse::notFound();
return ApiResponse::forbidden('You may not access this complex.');
return ApiResponse::validationError(errors: $validator->errors());

use HiTaqnia\Haykal\Core\ResultPattern\Error;

return ApiResponse::businessError(
    Error::make(code: 4001, message: 'Booking overlaps an existing reservation.'),
);

use HiTaqnia\Haykal\Api\Http\Middlewares\SetLocaleFromHeaderMiddleware;

// bootstrap/app.php
$middleware->appendToGroup('api', [
    new SetLocaleFromHeaderMiddleware(supported: ['en', 'ar']),
]);

// or a custom header:
new SetLocaleFromHeaderMiddleware(supported: ['en', 'ar'], header: 'X-Locale');

'guards' => [
    'api' => ['driver' => 'sanctum', 'provider' => 'users'],
],

// routes/api.php
use HiTaqnia\Haykal\Api\Auth\AuthRoutes;

Route::prefix('identity')
    ->middleware([SetLocaleFromHeaderMiddleware::class])
    ->group(fn () => AuthRoutes::register());

Route::middleware('throttle:identity')->group(function () {
    AuthRoutes::registerAccountCheck()  // tighter: it is an enumeration oracle
        ->middleware('throttle:identity-check');

    AuthRoutes::registerOtp();
    AuthRoutes::registerRegistration();
    AuthRoutes::registerSignIn();
});

Schedule::command('sanctum:prune-expired --hours=24')->daily();

use HiTaqnia\Haykal\Core\Identity\PhoneOrEmailCredentials;

protected function getCredentialsFromFormData(array $data): array
{
    return PhoneOrEmailCredentials::resolve($data['identity'], $data['password']) ?? [];
}

namespace App\Apis\Properties\Controllers;

use App\Apis\Properties\Requests\CreatePropertyRequest;
use App\Apis\Properties\Resources\PropertyResource;
use App\Domain\Properties\Actions\CreatePropertyAction;
use HiTaqnia\Haykal\Api\Response\ApiResponse;
use Illuminate\Http\JsonResponse;

final class CreatePropertyController
{
    public function __construct(
        private readonly CreatePropertyAction $createProperty,
    ) {}

    /**
     * Create Property
     *
     * Register a new property in the active tenant.
     *
     * @response PropertyResource
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function __invoke(CreatePropertyRequest $request): JsonResponse
    {
        $result = $this->createProperty->execute($request->validated());

        if ($result->isFailure()) {
            return ApiResponse::businessError($result->getError());
        }

        return ApiResponse::created(
            message: 'Property created.',
            data: new PropertyResource($result->getData()),
        );
    }
}

namespace App\Apis\Properties\Requests;

use HiTaqnia\Haykal\Core\Identity\Rules\PhoneNumberRule;
use Illuminate\Foundation\Http\FormRequest;

final class CreatePropertyRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('properties.create');
    }

    public function rules(): array
    {
        return [
            'name' => ['

namespace App\Apis\Properties\Resources;

use App\Domain\Properties\Models\Property;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @property Property $resource
 */
final class PropertyResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            // The property's unique identifier.
            // @var string
            // @format ULID
            'id' => $this->id,

            // The property's display name.
            'name' => $this->name,

            // ISO-8601 timestamp of when the property was registered.
            'created_at' => $this->created_at->toIso8601String(),
        ];
    }
}

public function test_create_property_returns_the_created_resource(): void
{
    $user = User::factory()->create();

    $response = $this->withBearer($token)->postJson('/api/properties', [
        'name' => 'Al-Mansour Tower',
        'owner_phone' => '+9647701234567',
    ]);

    $this->assertApiSuccess($response, code: 201);
    $response->assertJsonPath('data.name', 'Al-Mansour Tower');
}

routes/api/properties-api/v1.php
routes/api/properties-api/v2.php
bash
php artisan vendor:publish --tag=haykal-auth-config
php artisan vendor:publish --tag=haykal-auth-migrations
php artisan migrate

app/Apis/Properties/
    Controllers/
        CreatePropertyController.php
        ListPropertiesController.php
    Requests/
        CreatePropertyRequest.php
    Resources/
        PropertyResource.php

routes/api/properties-api.php