ユーザ用ツール

サイト用ツール


サイドバー

プログラム言語:php:laravel:laravel8:filemaxsize

【Laravel】バリデーションルールの追加(make:rule)

ファイルアップロート時にメガバイト(MB)単位でMaxサイズバリデーションを行う。

# バリデーションルールの追加
php artisan make:rule ImageFileMaxSize

app\Rules\ImageFileMaxSize.php

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ImageFileMaxSize implements Rule
{
    const MAX_MB = 10;      // メガバイト

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (is_null($value)) {
            return true;
        }

        // ファイルサイズをMBに変換
        $mega_bytes = $value->getSize() / 1024 / 1024;

        return $mega_bytes <= $this::MAX_MB;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute のサイズは' . $this::MAX_MB . 'MB以下にしてください。';
    }
}

追加したバリデーションルールの使い方

use App\Rules\ImageFileMaxSize;

    public function rules()
    {
        return [
            'file' => [
                'file',
                'image',
                'mimes:jpeg,jpg,png,gif',
                new ImageFileMaxSize,
            ],
        ];
    }

コメント

コメントを入力. Wiki文法が有効です:
 
プログラム言語/php/laravel/laravel8/filemaxsize.txt · 最終更新: 2022/05/12 19:08 by humolife