定制 opscale-co/validations 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

opscale-co/validations

Composer 安装命令:

composer require opscale-co/validations

包简介

Model validation for Laravel application.

README 文档

README

At Opscale, we're passionate about contributing to the open-source community by providing solutions that help businesses scale efficiently. If you've found our tools helpful, here are a few ways you can show your support:

Star this repository to help others discover our work and be part of our growing community. Every star makes a difference!

💬 Share your experience by leaving a review on Trustpilot or sharing your thoughts on social media. Your feedback helps us improve and grow!

📧 Send us feedback on what we can improve at feedback@opscale.co. We value your input to make our tools even better for everyone.

🙏 Get involved by actively contributing to our open-source repositories. Your participation benefits the entire community and helps push the boundaries of what's possible.

💼 Hire us if you need custom dashboards, admin panels, internal tools or MVPs tailored to your business. With our expertise, we can help you systematize operations or enhance your existing product. Contact us at hire@opscale.co to discuss your project needs.

Thanks for helping Opscale continue to scale! 🚀

Description

Model validation for Laravel applications. An easy validator option for your Eloquent models with flexibility for additional code that can be executed before and after validation.

The package exposes two public symbols:

Symbol Kind Purpose
Opscale\Validations\Validatable Trait Wires validation into Eloquent lifecycle events and runs optional beforeValidation / afterValidation hooks
Opscale\Validations\ModelValidator Class Resolves rules / messages / attributes / data from a model and runs Laravel's validator

All classes ship with declare(strict_types=1); and full type hints — your consuming code is expected to do the same.

Installation

Latest Version on Packagist

You can install the package via composer:

composer require opscale-co/validations

Usage

Here the User model is mentioned as an example. You can use this in any model you want.

Basic Setup

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Opscale\Validations\Validatable;

class User extends Model
{
    use Validatable;

    /** @var array<string, mixed> */
    public static array $validationRules = [
        'name' => 'required|max:10',
        'email' => 'required|email',
    ];

    protected static function booted(): void
    {
        // Validate the model on saving (runs on both create and update)
        static::validateOnSaving();
    }
}

Trait contract: if a model uses Validatable but declares no rules (neither static $validationRules nor a validationRules() method), calling validate() throws Opscale\Validations\Exceptions\MissingValidationRulesException. Using the trait is the explicit opt-in to validation — forgetting to declare rules is a configuration error, not a silent no-op.

Defining Rules, Messages, and Attributes

Rules, messages, and attributes can all be defined as static properties or instance methods. Methods take priority over properties and offer more flexibility when you need dynamic logic.

As static properties

/** @var array<string, mixed> */
public static array $validationRules = [
    'name' => 'required|max:10',
    'email' => 'required|email',
];

/** @var array<string, string> */
public static array $validationMessages = [
    'name.required' => 'Name field is required.',
    'email.email' => 'The given email is in invalid format.',
];

/** @var array<string, string> */
public static array $validationAttributes = [
    'name' => 'User Name',
];

As instance methods

/** @return array<string, mixed> */
public function validationRules(): array
{
    return [
        'name' => 'required|max:10',
        'email' => 'required|email',
    ];
}

/** @return array<string, string> */
public function validationMessages(): array
{
    return [
        'name.required' => 'Name field is required.',
        'email.email' => 'The given email is in invalid format.',
    ];
}

/** @return array<string, string> */
public function validationAttributes(): array
{
    return [
        'name' => 'User Name',
    ];
}

Context-Aware Rules (Create vs Update)

Each field can carry per-context rules. The context is resolved from $model->exists: new models use the create rule, persisted models use the update rule. A field whose context array does not include the current context is skipped entirely.

/** @var array<string, mixed> */
public static array $validationRules = [
    'name' => 'required|max:10',
    'email' => [
        'create' => 'required|email|unique:users',
        'update' => 'required|email',
    ],
    'token' => [
        'update' => 'required|min:32', // only enforced on update
    ],
];

Control the Data Being Validated

You can transform the data that gets validated by adding a validationData method:

/**
 * @param  array<string, mixed>  $data
 * @return array<string, mixed>
 */
public function validationData(array $data): array
{
    $data['name'] = mb_strtolower((string) $data['name']);

    return $data;
}

Before and After Validation Hooks

beforeValidation runs before Validator::make(). afterValidation runs only when validation succeeds — if validation throws Illuminate\Validation\ValidationException, afterValidation is skipped.

public function beforeValidation(): void
{
    // Normalize attributes, hydrate computed fields, etc.
}

public function afterValidation(): void
{
    // Side effects that should only run when the model is valid.
}

Validate on Specific Events

protected static function booted(): void
{
    // Validate only on creating
    static::validateOnCreating();

    // Or validate on any custom event
    static::updating(function (Model $model): void {
        $model->validate();
    });
}

Handling the Exceptions

Two exceptions can be thrown:

Exception Thrown when
Illuminate\Validation\ValidationException A validation rule fails
Opscale\Validations\Exceptions\MissingValidationRulesException The trait is used but no rules are declared on the model

The first is the standard Laravel exception — your existing exception handler will format it as a 422 JSON response automatically. The second is a RuntimeException and signals a configuration bug; let it surface in development.

Testing

The test suite uses Pest with Orchestra Testbench.

# Unit + Feature suites
npm test

# Individual suites
npm run test:unit
npm run test:feature

# Full pipeline: fix → refactor → lint → static analysis → test
npm run check

Static analysis runs at PHPStan level 8 with the four opscale-co/strict-rules rule sets (clean, ddd, smells, solid):

npm run analyse

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email development@opscale.co instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

opscale-co/validations 适用场景与选型建议

opscale-co/validations 是一款 基于 Shell 开发的 Composer 扩展包,目前已累计 395 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 opscale-co/validations 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 opscale-co/validations 我们能提供哪些服务?
定制开发 / 二次开发

基于 opscale-co/validations 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 395
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 29
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: Shell

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-08