1. Go to this page and download the library: Download api-skeletons/laravel-hal 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/ */
namespace App\HAL;
use ApiSkeletons\Laravel\HAL\HydratorManager as HALHydratorManager;
final class HydratorManager extends HALHydratorManager
{
public function __construct()
{
$this->classHydrators = [
\App\Models\Role::class => \App\HAL\Hydrator\RoleHydrator::class,
\App\Models\User::class => \App\HAL\Hydrator\UserHydrator::class,
];
}
namespace App\HAL\Hydrator;
use ApiSkeletons\Laravel\HAL\Hydrator;
use ApiSkeletons\Laravel\HAL\Resource;
use App\Models\User;
final class UserHydrator extends Hydrator
{
public function extract($class): Resource
{
$data = [];
$fields = [
'id',
'name',
'email',
];
// Extract fields into an array to be used by the resource
foreach ($fields as $field) {
$data[$field] = $class->$field;
}
// Create a new resource and assign self link and extract the
// roles into an embedded resource. Note `addEmbeddedResources`
// is used for arrays and `addEmbeddedResource` is used for classes
return $this->hydratorManager->resource($data)
->addLink('self', route('hal/user::fetch', $class->id))
->addEmbeddedResources('roles', $class->roles)
;
}
}
namespace App\HAL\Hydrator;
use ApiSkeletons\Laravel\HAL\Hydrator;
use ApiSkeletons\Laravel\HAL\Resource;
use App\Models\Role;
final class RoleHydrator extends Hydrator
{
public function extract($class): Resource
{
$data = [];
$fields = [
'id',
'name',
'guard_name',
];
// Extract fields into an array to be used by the resource
foreach ($fields as $field) {
$data[$field] = $class->$field;
}
// Create a new resource and assign self link and extract the
// roles into an embedded resource. Note `addEmbeddedResources`
// is used for arrays and `addEmbeddedResource` is used for classes
return $this->hydratorManager->resource($data)
->addLink('self', route('hal/role::fetch', $class->id))
;
}
}
public function fetch(User $user, Request $request)
{
$hydratorManager = new \App\HAL\HydratorManager();
return $hydratorManager->extract($user)->toArray();
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.