makaveli / laravel-core
Core for Laravel
Requires
- php: ^8.2
- laravel/framework: ^10.10|^11.0|^12.0
- makaveli/laravel-converter: 1.0.7
Requires (Dev)
- mockery/mockery: ^1.5
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2026-03-28 11:15:36 UTC
README
π 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-config
This 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.