/
itp_practice
/
itp_backend
Обзор
Документация
Войти
/
itp_practice
/
itp_backend
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
app/Http/Requests/CartRequest.php
100 строк
3 KB
vivanenko
cart
27 май 2025, 11:45
27 май 2025, 11:45
934cbb5
Код
Авторство
О чём код?
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CartRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return Auth::check(); } /** * Get the validation rules that apply to the request. */ public function rules(): array { $rules = []; switch ($this->getMethod()) { case 'POST': // Add to cart $rules = [ 'tariff_id' => [ 'required', 'integer', 'min:1', Rule::exists('tariffs', 'id')->where(function ($query) { $query->where('is_active', true); }), ], 'quantity' => [ 'integer', 'min:1', 'max:100', ], ]; break; case 'PUT': case 'PATCH': // Update quantity $rules = [ 'quantity' => [ 'required', 'integer', 'min:0', 'max:100', ], ]; break; } return $rules; } /** * Get custom messages for validator errors. */ public function messages(): array { return [ 'tariff_id.required' => 'Tariff ID is required', 'tariff_id.integer' => 'Tariff ID must be a valid integer', 'tariff_id.exists' => 'Selected tariff does not exist or is not active', 'quantity.required' => 'Quantity is required', 'quantity.integer' => 'Quantity must be a valid integer', 'quantity.min' => 'Quantity must be at least :min', 'quantity.max' => 'Quantity cannot exceed :max', ]; } /** * Get custom attributes for validator errors. */ public function attributes(): array { return [ 'tariff_id' => 'tariff', 'quantity' => 'quantity', ]; } /** * Handle a failed validation attempt. */ protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { throw new \Illuminate\Http\Exceptions\HttpResponseException( response()->json([ 'message' => 'Validation failed', 'errors' => $validator->errors(), ], 422) ); } }