You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+Livewire图片尺寸验证错误信息中如何显示上传图片尺寸

解决Laravel+Livewire图片尺寸验证自定义错误消息(含实际上传尺寸)

你可以通过两种方式实现需求,直接获取上传图片的实际宽高并插入到自定义错误消息中:

方法一:手动验证(快速实现)

不需要额外扩展规则,直接在Livewire组件的提交方法里手动检查图片尺寸,自定义错误信息:

public function submitForm()
{
    // 先验证基础规则:必填、是图片
    $this->validate([
        'banner_image' => 'required|image',
    ]);

    // 获取上传的图片文件
    $uploadedFile = $this->banner_image;
    // 用PHP原生函数获取宽高(无需额外依赖)
    [$uploadedWidth, $uploadedHeight] = getimagesize($uploadedFile->getPathname());

    // 检查是否符合指定尺寸
    $requiredWidth = 100;
    $requiredHeight = 200;
    if ($uploadedWidth !== $requiredWidth || $uploadedHeight !== $requiredHeight) {
        // 添加自定义错误消息
        $this->addError('banner_image', sprintf(
            'Wrong dimensions. Required dimensions are %dX%d and dimensions of file that you upload - %dX%d',
            $requiredWidth,
            $requiredHeight,
            $uploadedWidth,
            $uploadedHeight
        ));
        return; // 终止后续逻辑
    }

    // 验证通过,执行后续逻辑(比如保存图片)
    // ...
}

方法二:自定义验证规则(可复用)

如果需要在多个地方复用这个尺寸验证逻辑,可以创建自定义规则类:

  1. 生成规则文件:
php artisan make:rule BannerImageDimensions
  1. 编辑规则类app/Rules/BannerImageDimensions.php:
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class BannerImageDimensions implements Rule
{
    protected $requiredWidth;
    protected $requiredHeight;
    protected $uploadedWidth;
    protected $uploadedHeight;

    // 构造函数接收要求的宽高,默认值可自定义
    public function __construct(int $width = 100, int $height = 200)
    {
        $this->requiredWidth = $width;
        $this->requiredHeight = $height;
    }

    public function passes($attribute, $value)
    {
        // 获取上传图片的实际宽高
        [$this->uploadedWidth, $this->uploadedHeight] = getimagesize($value->getPathname());
        // 验证尺寸是否匹配
        return $this->uploadedWidth === $this->requiredWidth && $this->uploadedHeight === $this->requiredHeight;
    }

    public function message()
    {
        // 返回带实际尺寸的自定义错误消息
        return sprintf(
            'Wrong dimensions. Required dimensions are %dX%d and dimensions of file that you upload - %dX%d',
            $this->requiredWidth,
            $this->requiredHeight,
            $this->uploadedWidth,
            $this->uploadedHeight
        );
    }
}
  1. 在Livewire组件中使用该规则:
public function submitForm()
{
    $this->validate([
        'banner_image' => [
            'required',
            'image',
            new \App\Rules\BannerImageDimensions(100, 200) // 传入要求的宽高
        ],
    ]);

    // 验证通过后的逻辑
    // ...
}

注意事项

  • 确保服务器已安装GD或Imagick扩展(getimagesize依赖GD扩展);
  • 如果使用Intervention Image库处理图片,也可以用Image::make($uploadedFile)->width()和height()方法获取尺寸,效果一致。

内容的提问来源于stack exchange,提问作者user2265529

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:30:28