PHP code example of jeromejhipolito / laravel-api-versioning

1. Go to this page and download the library: Download jeromejhipolito/laravel-api-versioning 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/ */

    

jeromejhipolito / laravel-api-versioning example snippets


return [
    'supported_versions' => ['1.0.0', '1.1.0', '2.0.0'],
    'enabled_versions' => env('API_ENABLED_VERSIONS') 
        ? array_map('trim', explode(',', env('API_ENABLED_VERSIONS')))
        : null, // null = all supported versions enabled
    'default_version' => env('API_DEFAULT_VERSION', '1.0.0'),
];

use JeromeJHipolito\ApiVersioning\Middleware\ApiVersionMiddleware;
use JeromeJHipolito\ApiVersioning\Middleware\ResolveVersionedController;

->withMiddleware(function (Middleware $middleware) {
    $middleware->api(append: [
        ApiVersionMiddleware::class,
        ResolveVersionedController::class,
    ]);
})

use JeromeJHipolito\ApiVersioning\Traits\VersionAwareTrait;

class UserController extends Controller
{
    use VersionAwareTrait;

    public function show($id)
    {
        $user = User::find($id);
        
        // Check version
        if ($this->isVersionAtLeast('2.0.0')) {
            return new V2\UserResource($user);
        }
        
        return new UserResource($user);
    }
}

use JeromeJHipolito\ApiVersioning\Traits\VersionAwareResourceTrait;

class UserResource extends JsonResource
{
    use VersionAwareResourceTrait;

    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            
            // Only in 1.1.0+
            ...$this->mergeWhenVersion('1.1.0', [
                'profile_score' => $this->profile_score,
            ]),
            
            // Only below 2.0.0 (deprecated)
            ...$this->mergeWhenVersionBelow('2.0.0', [
                'legacy_field' => $this->old_data,
            ]),
        ];
    }
}

   'supported_versions' => ['1.0.0', '2.0.0'],
   

use JeromeJHipolito\ApiVersioning\Middleware\MinimumVersionMiddleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'min.version' => MinimumVersionMiddleware::class,
    ]);
})

// Single route
Route::post('new-feature', [FeatureController::class, 'store'])
    ->middleware('min.version:1.1.0');

// Route group
Route::group(['middleware' => ['min.version:2.0.0']], function () {
    Route::post('advanced', [AdvancedController::class, 'store']);
    Route::delete('advanced/{id}', [AdvancedController::class, 'destroy']);
});
bash
php artisan vendor:publish --tag=api-versioning-config
php artisan vendor:publish --tag=api-versioning-lang