Старая валидация (размеры) — Laravel

Сегодня мы познакомимся с очень важной вещью — валидацией, которая позволяет контролировать размеры изображений, загружаемых в наш проект. В чем-то она старая, но некоторым разработчикам она неизвестна.
Посетите источники :-
https://laravel.com/docs/9.x/validation#rule-dimensions
https://mattstauffer.com/blog/image-dimension-validation-rules-in-laravel-5-3/

  • Здесь мы узнаем о свойствах, которые мы будем использовать при проверке размеров изображения
In Laravel 5.3, we have a new validation option: image dimensions for image uploads
The validation rule is called dimensions, and you can pass the following parameters to it 

min_width: Images narrower than this pixel width will be rejected
max_width: Images wider than this pixel width will be rejected
min_height: Images shorter than this pixel height will be rejected
max_height: Images taller than this pixel height will be rejected
width: Images not exactly this pixel width will be rejected
height: Images not exactly this pixel height will be rejected
ratio: Images not exactly this ratio (width/height, expressed as "width/height") will be rejected

Вход в полноэкранный режим Выход из полноэкранного режима
  • Теперь давайте создадим наш ImageController и посмотрим на несколько примеров валидации
 public function postImage(Request $request)
 {
        $this->validate($request, [
             'avatar' => 'dimensions:min_width=250,min_height=500'
        ]);

        // or... 

        $this->validate($request, [
             'avatar' => 'dimensions:min_width=500,max_width=1500'
        ]);

        // or...

        $this->validate($request, [
             'avatar' => 'dimensions:width=100,height=100'
        ]);

        // or...

        // Ensures that the width of the image is 1.5x the height
        $this->validate($request, [
             'avatar' => 'dimensions:ratio=3/2'
        ]);
}
Вход в полноэкранный режим Выход из полноэкранного режима
  • использование метода Rule::dimensions для беглого построения правила
use IlluminateSupportFacadesValidator;
use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);
Вход в полноэкранный режим Выход из полноэкранного режима

Надеюсь, вам понравился код, и я желаю вам счастливого кода.

Оцените статью
devanswers.ru
Добавить комментарий