laravel-core maintained by makaveli
makaveli/laravel-core
🌍 Languages
- 🇺🇸 English (default)
- 🇷🇺 Русская версия
Contents
Introduction
The makaveli/laravel-core library provides a foundational set of tools for developing applications on the Laravel framework. It simplifies working with data, models, requests, validation, and other aspects of backend development, providing a unified approach to handling forms, lists, as well as support for soft deletes and user action logging.
The main goals of the library are:
- Standardizing data access through repositories and services.
- Unified DTOs for forms, lists, and single operations.
- Automatic determination of user context (organization, role).
- Support for soft deletes with action auditing.
- Ready-made validation rules and helpers for typical tasks.
- Easy integration with Laravel 10+ and PHP 8.2+.
The library is licensed under MIT and developed by Michael Udovenko.
Installation
-
Install the library via Composer:
composer require makaveli/laravel-core -
Publish the configuration file:
php artisan vendor:publish --tag=core-configThis will create a
config/core.phpfile in your project. -
Register the service provider in
config/app.php(if not registered automatically):'providers' => [ // ... \Core\Providers\CoreServiceProvider::class, ], -
Ensure the
makaveli/laravel-converterdependency is installed (version 1.0.6 or higher). It is used for converting array keys.
Configuration
The config/core.php file contains settings for all components. The main sections are listed below:
log– the class for logging errors (default\Illuminate\Support\Facades\Log::class).list_dto.default_request_fields– fields automatically extracted from the request for lists.form_dto.common_request_fields– fields common to all forms (e.g.,organizationId).form_dto.context_resolver– the class that determinesorganization_idandrole_idfor DTOs.repository– repository settings (field for the root user, user ID).exception– default messages for various exception types.response– messages for successful and error API responses.soft-model-base– settings for models with soft deletes (keys forcreated_by,updated_by,deleted_byand the user model class).rules– messages for custom validation rules.validators– messages for date range validators.
A full description of all parameters can be found in the generated config/core.php file.
Core Components
The library is divided into modules within the Core namespace. Each module is described in detail in a separate documentation file.
Exceptions
Base classes for throwing errors with a specific error and message.
DTO
DTOs are used to transfer data between application layers. They integrate with authentication and context resolvers.
- DynamicDTO – dynamic DTO for arbitrary data with user context.
- ExecutionOptionsDTO – execution options (transactions, validation, logging).
- FormDTO – base DTO for create/update operations.
- ListDTO – DTO for lists with filtering and pagination.
- OnceDTO – DTO for operations on a single entity.
Helpers
Helper classes for normalizing and transforming data.
- Filters – transforming boolean values.
- Paginations – generating empty pagination.
- Phone – cleaning phone numbers from extra symbols.
- Relations – working with relationships (transforming
hasManyintohasOne).
Http
Abstractions for working with HTTP requests.
- LaravelHttpContext – implementation of
IHttpContext, encapsulating access to the current Laravel request.
Models
Base models and traits.
- SoftModelBase – base model with soft deletes and action auditing.
Repositories
Base repository for working with Eloquent models.
- BaseRepository – contains over 70 methods for CRUD, aggregations, caching, working with soft deletes, and complex filters.
Requests
Base class for form requests.
- BaseFormRequest – supports contexts (CREATE, UPDATE, DELETE) and automatic transformation into DTOs.
Resources
Base class for JSON resources.
- BaseResource – allows lazy loading of additional fields in API responses.
Responses
Utility class for standardized JSON responses.
- ApiResponse – methods like
success(),error(),unauthorized(),notFound(), and others with a unified format.
Rules
Custom validation rules.
- ValidFlatNumberOrRange – validating a flat number (single number or range).
- ValidPassword – validating password complexity.
- ValidRuPhone – validating a Russian phone number.
Services
Base service for business logic.
- BaseService – contains over 60 methods for creating, updating, deleting, bulk operations, working with JSON fields, hashing, etc.
Traits
Traits for extending model functionality.
- ActionInfo – adds
creator,updator,deletorrelationships. - SoftModel – implements soft delete/restore with transactions and logging.
Validators
Validators for date ranges.
- DateRangeValidator – checking correctness and order of dates (with or without time).
Examples
Creating a Repository
use Core\Repositories\BaseRepository;
class ArticleRepository extends BaseRepository
{
public function __construct()
{
parent::__construct(Article::class);
}
}
$repo = new ArticleRepository();
$article = $repo->findByIdOrFail(1);
$list = $repo->getPaginatedList(ListDTO::fromRequest($request));
Creating a Service
use Core\Services\BaseService;
class ArticleService extends BaseService
{
public function __construct()
{
parent::__construct(Article::class);
}
}
$service = new ArticleService();
$newArticle = $service->create(['title' => 'New article', 'content' => '...']);
$updatedArticle = $service->update($article, ['title' => 'Updated']);
$service->softDelete($article);
Form DTO
use Core\DTO\FormDTO;
class UserFormDTO extends FormDTO
{
public function __construct(
public readonly string $name,
public readonly string $email,
Authenticatable $user,
?int $organizationId,
?int $roleId,
?int $id = null,
) {
parent::__construct($user, $organizationId, $roleId, $id);
}
public static function fromRequest(UserRequest $request, ?int $id = null): static
{
$baseData = self::processBaseData($request, $id, ['name', 'email']);
return new static(
name: $baseData['converted_data']['name'],
email: $baseData['converted_data']['email'],
user: $baseData['user'],
organizationId: $baseData['organization_id'],
roleId: $baseData['role_id'],
id: $baseData['id'],
);
}
}
Using a Validation Rule
use Core\Rules\ValidRuPhone;
class UserRequest extends BaseFormRequest
{
protected function rulesFor(Context $context): array
{
return [
'phone' => ['required', new ValidRuPhone],
'password' => ['required', new ValidPassword],
];
}
}
API Response
use Core\Responses\ApiResponse;
public function show($id): JsonResponse
{
$user = User::find($id);
if (!$user) {
return ApiResponse::notFound('User not found');
}
return ApiResponse::success($user);
}
Recommendations
- Always use DTOs to transfer data between application layers.
- Inherit models from
SoftModelBaseif soft deletes and auditing are required. - For read operations, use repositories; for write operations, use services.
- Use
BaseFormRequestfor data validation with context (create/update). - Use
BaseResourcewith lazy loading of additional fields to optimize API responses. - For complex filters, extend
ListDTOwith custom parameters. - Configure the context resolver in the configuration file if your application has a different logic for determining the organization and role.