Models - KroderDev/laravel-microservice-core GitHub Wiki
The package includes an abstract base model for calling your API gateway.
Extend Kroderdev\LaravelMicroserviceCore\Models\Model
to create a resource model.
Creating a model
use Kroderdev\LaravelMicroserviceCore\Models\Model as ApiModel;
class User extends ApiModel
{
protected $fillable = ['id', 'name'];
}
By default the endpoint is the plural kebab case of the class name (e.g. /users
).
Override the $endpoint
property to customize it:
class Article extends ApiModel
{
protected static string $endpoint = '/posts';
}
Remote model generator
Run the command with --remote
to create a model that already extends the package base model:
php artisan make:model Order --remote
Available methods
all()
– fetch a collection of modelsfind($id)
– retrieve a model by its keypaginate($perPage = 15)
– return a paginatorcreate(array $attributes)
– create via the APIsave()
– update or createdelete()
– remove via the APIrefresh()
– reload from the API
Traits
The model already uses ApiModelTrait
which provides helpers like fromApiResponse
,
fromCollection
and fromPaginatedResponse
.
User models that store roles and permissions can also use the HasAccess
trait
to gain hasRole
, hasPermissionTo
and related helpers.
Integration with ApiGateway
By default, models are configured to fetch data directly from the ApiGateway. Ensure that your ApiGateway is properly set up and configured so that models can seamlessly interact with remote resources. This integration allows your models to retrieve and manipulate data consistently across your microservices architecture. For more details, see [ApiGateway].
Defining relations
Models can automatically hydrate nested relations by defining the $apiRelations
property. It maps relation names from the API to local model classes:
use Kroderdev\LaravelMicroserviceCore\Models\Model as ApiModel;
class Post extends ApiModel
{
protected $fillable = ['id', 'title', 'comments'];
protected static array $apiRelations = [
'comments' => Comment::class,
];
}
For nested structures or custom property names you can provide a callback that receives the relation value and must return a collection or model instance:
use Kroderdev\LaravelMicroserviceCore\Models\Model as ApiModel;
class Post extends ApiModel
{
protected $fillable = ['id', 'title', 'comments'];
protected static array $apiRelations = [
'comments' => Comment::class,
'author' => 'mapAuthor',
'likes' => 'mapLikes',
];
protected static function mapAuthor(array $data): User
{
return User::fromApiResponse($data['profile']);
}
protected static function mapLikes(array $data): Collection
{
return collect($data)->map(function ($item) {
return new Like($item);
});
}
}
The mapping is applied when calling fromApiResponse
, fromCollection
or fromPaginatedResponse
.