laravel-working-group/laravel-form-requests-improved 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

laravel-working-group/laravel-form-requests-improved

Composer 安装命令:

composer require laravel-working-group/laravel-form-requests-improved

包简介

Supercharges your FormRequest class

README 文档

README

  1. Installation
  2. Compound validation rules
    1. Don't
    2. Do
    3. Available compound rules
  3. Fluent validation rules
  4. FormRequest union type dependency injection in controller methods
  5. Post-validation sanitization

Installation

composer install laravel-working-group/laravel-form-requests-improved

Compound validation rules

When you have a FormRequest like this,

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'foo' => 'require_without:bar',
        ];
    }
}

it's usually not just this, but actually also the other way round:

public function rules(): array
{
    return [
        'foo' => 'require_without:bar',
        'bar' => 'require_without:foo',
    ];
}

often times even with the negated role for each:

public function rules(): array
{
    return [
        'foo' => [ 'require_without:bar', 'prohibits:bar' ],
        'bar' => [ 'require_without:foo', 'prohibits:foo' ],
    ];
}

this is quite a lot for actually just one rule and we can easily forget to add one or multiple of these but due to the nature of how FormRequests work, we can't really chance that. However, we can use syntactic sugar for this:

use LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\FormRequest;

// ...

public function rules(): array
{
    return [
        self::prohibitEither('foo', 'bar'),
        self::requireEither('foo', 'bar'),
    ];
}

or even just:

public function rules(): array
{
    return [
        self::eitherOr('foo', 'bar'),
    ];
}

⚠️ WARNING\ Make sure to extend your request from LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\FormRequest and not from Laravel's Illuminate\Foundation\Http\FormRequest. Don't worry, it itself extends from Laravel's FormRequest so you can do everything you can also do with Laravel's FormRequest and more.

If for some reason, you don't want are are unable to use LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\FormRequest, you can alternatively use the LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\Concerns\ValidateCompoundRules concern directly.

⚠️ WARNING\ Avoid using array_merge() or the + operator on these, because that would overwrite rules for the same field:

❌ Don't

public function rules(): array
{
    return [
        self::requireEither('foo', 'bar'),
        'foo' => 'string'
    ];
}

That would result in the final result being

[
    'foo' => 'string'
]

Because requireEither() generates the following:

[
    'foo' => 'require_without:bar',
    'bar' => 'require_without:foo',
]

which then would be overwritten by

[
    'foo' => 'string'
]

✅ Do

public function rules(): array
{
    return [
        self::requireEither('foo', 'bar'),
        [ 'foo' => 'string' ]
    ];
}

Internally, this will be merged by array_merged_recursive().

⚠️ WARNING\ The array_merged_recursive() call is not part of Illuminate\Foundation\Http\FormRequest. You need to use LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\FormRequest for this. If you don't want or unable to use it, you need to overwrite the validationRules() method on your own.

Available compound rules

RuleCompound of
prohibitEitherprohibits
requireEitherrequired_without
eitherOrprohibits and required_without
beforeAfterbefore and after

Fluent validation rules

Ever wanted to define a rule neither with array nor string syntax but object-oriented? This can be done with fluent validation rules!

So, instead of this:

public function rules(): array
{
    return [
        'error' => [ 'string', 'required', 'max:30' ],
        'avatar' => [ 'dimensions:min_width=100' ],
    ];
}

you can do this:

use Illuminate\Validation\Rules\Dimensions;

use function LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\image;
use function LaravelWorkingGroup\ImprovedFormRequests\Foundation\Http\string;

// …

public function rules(): array
{
    return [
        'error' => string()->required()->length(max: 30),
        'avatar' => image()->dimensions(fn(Dimensions $dimensions) => $dimensions->minWidth(50)),
    ];
}

FormRequest union type dependency injection in controller methods

Ever had the case where a third-party service would call a webhook in your API but you would not know the exact format, because there would be one format if the action the service executed and informs you about was successful and an entirely different format when it failed?

In Laravel, you have no way to solve this cleanly. However, with this package, you can just use the service container attribute LaravelWorkingGroup\ImprovedFormRequests\Container\Attributes\FormRequest:

<?php

namespace App\Http\Controllers;

use LaravelWorkingGroup\ImprovedFormRequests\Container\Attributes\FormRequest;
use App\Http\Requests\FailedWebhook;
use App\Http\Requests\SuccessfulWebhook;
use Symfony\Component\HttpFoundation\Response;

class WebhookController
{
    public function webhook(
        #[FormRequest(FailedWebhook::class, SuccessfulWebhook::class)] $request
    )
    {
        // $request can be either `App\Http\Requests\FailedWebhook` or `App\Http\Requests\SuccessfulWebhook`
        // and can contain either `error` and `message`, or `id` and `name` in our case
        if ($request instanceof FailedWebhook) {
            return response("[{$request->error}] {$request->message}", Response::HTTP_BAD_REQUEST);
        }

        [ 'id' => $id, 'name' => $name ] = $request->validated();
    }
}

Post-validation sanitization

You can also sanitize your data after the validation has been successful and before the FormRequest is passed to the controller, so you can simply get data from the request without having to worry about the data type in the controller.

public function sanitizationRules(): bool|array
{
    return [
        'error_code' => 'int',
        'error_message' => 'string',
        'id' => 'model:user',
    ];
}

So this results in:

<?php
public function webhook(WebhookFormRequest $request)
{
    dd($request->all());
    /*
        [
            'error_code' => 500,
            'error_message' => \Illuminate\Support\Stringable('Unwanted'),
            'id' => \App\Models\User(1),
        ]
    */
}

You can even let the FormRequest infer the sanitization rule of a field for you:

public function rules(): array {
    return [
        'error_code' => 'integer',
    ];
}

public function sanitizationRules(): bool|array
{
    return [
        'error_code' => true,
    ];
}

This will infer 'int' as a sanitization rule and cast the value accordingly.

You can also let the FormRequest infer all sanitization rules like this:

public function sanitizationRules(): bool|array
{
    return true;
}

laravel-working-group/laravel-form-requests-improved 适用场景与选型建议

laravel-working-group/laravel-form-requests-improved 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 laravel-working-group/laravel-form-requests-improved 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: LGPL-2.1-only
  • 更新时间: 2025-01-17