Validatsiya, import va eksport
Ta’minot bo‘limi 3 000 qatorli Excel fayl yubordi: “mana yangi narxlar”. Uni OmborPro ga qanday kiritasiz?
Hozircha javob bermang. Faylda nimalar noto‘g‘ri bo‘lishi mumkinligini o‘ylab ko‘ring.
Bu ma’ruza oxirida siz quyidagilarni bajara olasiz...
prepareForValidation, rules, after, maxsus qoida (ValidationRule)maatwebsite/excel bilan mahsulotlar va kontragentlar importini (WithHeadingRow, WithValidation, SkipsOnFailure)import_batches jadvali va xatolar ro‘yxatiFromQuery, WithHeadings, WithMapping)Validatsiya: Form Request va qoidalar
StoreProductRequest: normallash va qoidalar
// class StoreProductRequest extends FormRequest protected function prepareForValidation(): void { $this->merge(['sku' => strtoupper(trim((string) $this->sku))]); } public function rules(): array { return [ 'sku' => ['required', 'regex:/^[A-Z]{2,4}-\d{3,6}$/', Rule::unique('products')->ignore($this->product)], 'name' => ['required', 'string', 'max:255'], 'category_id' => ['required', 'exists:categories,id'], 'unit' => ['required', Rule::in(Product::UNITS)], 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0'], 'min_stock' => ['nullable', 'integer', 'min:0'], ]; }
POST /products sku=" un-001 ", price="12.345"
→ sku "UN-001" ga normallandi
→ 302 back, errors: price — “2 ta o‘nli xonadan oshmasin”
(JSON so‘rovda: 422 {"errors": {"price": [...]}})| bo‘lsa qoidalar bo‘linib ketadisku); ignore($this->product) — update da o‘zi bilan to‘qnashmaydi['dona', 'kg', 'litr', 'quti'] — modeldagi konstanta, bitta manbanumeric bilan birga min:0 son sifatida tekshiriladiSTIR (INN) qoidasi — ValidationRule
namespace App\Rules; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class Inn implements ValidationRule { public function validate( string $attribute, mixed $value, Closure $fail ): void { if (! is_string($value) || ! preg_match('/^\d{9}$/', $value)) { $fail(':attribute 9 ta raqamdan iborat bo‘lishi kerak.'); } } } // 'inn' => ['required', new Inn(), // Rule::unique('counterparties', 'inn')],
$ php artisan make:rule Inn INFO Rule [app/Rules/Inn.php] created successfully. inn = "30512345" → “STIR 9 ta raqamdan iborat bo‘lishi kerak.”
app/Rules/Inn.php — ValidationRule shabloni:attribute o‘rniga maydon nomi qo‘yiladiNormallash, keyin tekshirish
function normalize(array $r): array { $r['sku'] = strtoupper(strtr(trim($r['sku'] ?? ''), ' _', '--')); $r['name'] = trim(preg_replace('/\s+/', ' ', $r['name'] ?? '')); return $r; } function errors(array $r): string { $money = '/^\d+(\.\d{1,2})?$/'; $e = []; if (!preg_match('/^[A-Z]{2,4}-\d{3,6}$/', $r['sku'])) $e[] = 'sku'; if ($r['name'] === '') $e[] = 'name'; if (!preg_match($money, $r['price'] ?? '')) $e[] = 'price'; return '[' . implode(',', $e) . ']'; } $a = normalize(['sku' => 'un 001', 'name' => 'Un 1', 'price' => '9']); echo json_encode($a), ' → ', errors($a), PHP_EOL; echo errors(normalize(['sku' => 'UN1', 'price' => '-5'])), PHP_EOL;
{"sku":"UN-001","name":"Un 1","price":"9"} → []
[sku,name,price]_ → -: un 001 → UN-001-5 o‘tmaydiprepareForValidation kabiOmborPro maydonlari uchun qoidalar
| Maydon | Qoidalar | Izoh |
|---|---|---|
sku | required, regex, Rule::unique()->ignore() | normallash prepareForValidation da |
price, total | numeric, decimal:0,2, min:0 | pul — float emas, decimal |
inn | required, new Inn(), unique | 9 raqam, kontragentlar orasida yagona |
type | Rule::in(['customer', 'supplier', 'both']) | kontragent turi |
phone | required_if:type,customer, regex:/^\+998\d{9}$/ | mijoz uchun majburiy |
items.*.product_id | required, distinct, exists:products,id | buyurtma qatorlari |
due_at | date, after_or_equal:issued_at | to‘lov muddati |
file | file, mimes:xlsx,csv, max:10240 | max — kilobaytda |
required + nullable farqi: nullable — maydon bo‘lishi mumkin, lekin null ga ruxsat; sometimes — faqat kelganda tekshir.1-bo‘lim yakuni: Validatsiya: Form Request va qoidalar
prepareForValidation() qachon bajariladi va unda nima qilinadi?regex qoidasi bor bo‘lsa, qoidalarni massiv ko‘rinishida yozish kerak?1-topshiriq: SKU ni normallashtirish
Foydalanuvchi SKU ni turlicha yozadi: un_001 , sh 0105, UN--001. prepareForValidation mantiqini yozing: chetdagi bo‘sh joylarni olib tashlang, katta harfga o‘tkazing, bo‘sh joy va _ belgilarini - ga almashtiring, ketma-ket kelgan bir nechta - ni bitta qiling. Natija ^[A-Z]{2,4}-\d{3,6}$ andozasiga (2–4 lotin harfi, chiziqcha, 3–6 raqam) mos kelmasa — InvalidArgumentException.
Imzo: function sku_normallash(string $sku): string
Qaytaradi: Normallangan SKU satri, masalan UN-001.
sku_normallash(' un_001 ')"UN-001"
Ma’lumotlar yaxlitligi: bazadagi cheklovlar
Kim nimani ushlaydi?
1Form Request
decimal:0,2, exists. Foydalanuvchiga chiroyli xabar.2Servis qatlami
3Baza
UNIQUE, FOREIGN KEY, CHECK, NOT NULL. Har qanday yo‘l bilan kelgan ma’lumotni ushlaydi.4Tranzaksiya
PostgreSQL CHECK cheklovlari
return new class extends Migration { public function up(): void { DB::statement('ALTER TABLE stocks ADD CONSTRAINT chk_stock CHECK (reserved >= 0 AND quantity >= reserved)'); DB::statement('ALTER TABLE products ADD CONSTRAINT chk_price CHECK (price >= 0)'); DB::statement('ALTER TABLE invoices ADD CONSTRAINT chk_paid CHECK (paid_amount BETWEEN 0 AND total)'); } public function down(): void { DB::statement('ALTER TABLE stocks DROP CONSTRAINT chk_stock'); DB::statement('ALTER TABLE products DROP CONSTRAINT chk_price'); DB::statement('ALTER TABLE invoices DROP CONSTRAINT chk_paid'); } };
UPDATE stocks SET reserved = 12 WHERE id = 5; -- quantity = 10 ERROR: new row for relation "stocks" violates check constraint "chk_stock" DETAIL: Failing row contains (5, 1, 15, 10, 12).
UNIQUE buzilishini tushunarli xatoga aylantirish
public function store(StoreProductRequest $request) { try { $product = Product::create($request->validated()); } catch (UniqueConstraintViolationException $e) { // validatsiyadan o‘tdi, lekin parallel so‘rov ulgurdi throw ValidationException::withMessages([ 'sku' => 'Bu SKU bilan mahsulot hozirgina yaratildi.', ]); } return redirect()->route('products.show', $product) ->with('status', 'Mahsulot qo‘shildi'); }
So‘rov A: unique ✓ → INSERT ✓ → 302 products/51
So‘rov B: unique ✓ → INSERT ✗ (23505 unique_violation)
→ 302 back, errors.sku: “Bu SKU bilan mahsulot hozirgina yaratildi.”QueryException ning aniq turi2-bo‘lim yakuni: Ma’lumotlar yaxlitligi: bazadagi cheklovlar
unique:products,sku validatsiya qoidasi bo‘lsa ham bazada UNIQUE indeks kerak?withoutTrashed() li unique qoidasi va oddiy UNIQUE indeks birga qanday muammo tug‘diradi?2-topshiriq: Mahsulot validatsiyasi (xatolar lug‘ati)
Form Request ga o‘xshash tekshiruvchi yozing. Kirish — maydonlar massivi (qiymatlar satr yoki son). Maydonlar shu tartibda tekshiriladi va har biriga ko‘pi bilan bitta xabar: sku — yo‘q/bo‘sh: “SKU majburiy”, andozaga (^[A-Z]{2,4}-\d{3,6}$, trim dan keyin) mos emas: “SKU formati noto‘g‘ri”; name — bo‘sh: “Nomi majburiy”, 255 baytdan uzun: “Nomi juda uzun”; unit — dona, kg, litr, quti dan biri emas: “Birlik noto‘g‘ri”; price — manfiy bo‘lmagan, ko‘pi bilan 2 o‘nli xonali son (^\d+(\.\d{1,2})?$) emas: “Narx noto‘g‘ri”; min_stock — ixtiyoriy, berilgan bo‘lsa faqat raqamlar: “Minimal qoldiq noto‘g‘ri”.
Imzo: function mahsulot_xatolari(array $r): array
Qaytaradi: ['maydon' => ['xabar'], ...] — faqat xatoli maydonlar, yuqoridagi tartibda; xato yo‘q bo‘lsa [].
mahsulot_xatolari(['sku' => 'UN-001', 'name' => 'Un oliy nav', 'unit' => 'dona', 'price' => '385000'])
[]
Ommaviy import: maatwebsite/excel
Import sinfiga nimani qo‘shamiz?
| Concern | Nima beradi | Metod / trait |
|---|---|---|
ToModel | har bir qator → Eloquent model | model(array $row) |
ToCollection | qatorlarni o‘zingiz qayta ishlaysiz | collection(Collection $rows) |
WithHeadingRow | sarlavhalar kalit bo‘ladi (slug) | headingRow(): int (ixtiyoriy) |
WithValidation | har qatorga Laravel qoidalari | rules(), prepareForValidation() |
SkipsOnFailure | xato qatorlar o‘tkaziladi, yig‘iladi | SkipsFailures → failures() |
WithChunkReading | fayl bo‘laklab o‘qiladi | chunkSize(): int |
WithBatchInserts | guruhlab INSERT | batchSize(): int |
WithUpserts | mavjud bo‘lsa yangilash | uniqueBy() — 'sku' |
SkipsOnFailure bo‘lmasa, birinchi yaroqsiz qatorda ValidationException tashlanadi va import to‘xtaydi.ProductsImport
class ProductsImport implements ToModel, WithHeadingRow, WithValidation, SkipsOnFailure, WithChunkReading { use Importable, SkipsFailures; public int $okRows = 0; public function model(array $row): ?Product { $this->okRows++; // faqat validatsiyadan o‘tganlar return new Product([ 'sku' => strtoupper(trim($row['sku'])), 'name' => $row['nomi'], 'unit' => $row['birlik'], 'price' => $row['narx'], 'category_id' => $row['kategoriya_id'], ]); } public function chunkSize(): int { return 1000; } }
Shablon: | sku | nomi | kategoriya_id | birlik | narx | min_qoldiq |
$row = ['sku' => 'UN-001', 'nomi' => 'Un oliy nav, 50 kg',
'kategoriya_id' => 3, 'birlik' => 'dona', 'narx' => 385000, ...]$row['nomi'] — ustun raqami emas, sarlavha nomifailures() to‘plamiga tushadiQatorlar uchun rules va prepareForValidation
public function prepareForValidation(array $data, int $index): array { $data['sku'] = strtoupper(trim((string) ($data['sku'] ?? ''))); $data['narx'] = str_replace([' ', ','], ['', '.'], (string) ($data['narx'] ?? '')); return $data; } public function rules(): array { return [ 'sku' => ['required', 'regex:/^[A-Z]{2,4}-\d{3,6}$/', 'unique:products,sku'], 'nomi' => ['required', 'string', 'max:255'], 'birlik' => ['required', 'in:dona,kg,litr,quti'], 'narx' => ['required', 'numeric', 'min:0'], 'kategoriya_id' => ['required', 'exists:categories,id'], ]; }
Failure: row() = 7, attribute() = 'narx',
errors() = ['The narx field must be a number.'],
values() = ['sku' => 'SH-010', 'narx' => 'kelishilgan', ...]CSV qatorini o‘qish va normallash
<?php $csv = "sku;nomi;narx\nUN-001;Un oliy nav;385 000\n" . "SH-010;\"Shakar; 1 kg\";14 500,50\n"; $lines = array_values(array_filter(explode("\n", $csv))); $head = str_getcsv(array_shift($lines), ';', '"', ''); foreach ($lines as $i => $line) { $row = array_combine($head, str_getcsv($line, ';', '"', '')); $row['narx'] = str_replace([' ', ','], ['', '.'], $row['narx']); printf("%d-qator: %s | %s | %s\n", $i + 2, $row['sku'], $row['nomi'], $row['narx']); }
2-qator: UN-001 | Un oliy nav | 385000 3-qator: SH-010 | Shakar; 1 kg | 14500.50
;; qo‘shtirnoq ichidagi ; maydon qismiWithHeadingRow kabi3-bo‘lim yakuni: Ommaviy import: maatwebsite/excel
ToModel va ToCollection concern larining farqi nimada?Failure obyektidan hisobot uchun qanday ma’lumotlarni olamiz?3-topshiriq: Sarlavhadan kalit (heading row)
WithHeadingRow sarlavhalarni kalitga aylantiradi. Soddalashtirilgan variantini yozing: chetdagi bo‘sh joylarni olib tashlang, o‘zbekcha tutuq va o‘ belgilari (‘, ’, ʻ, ASCII ') ni olib tashlang, kichik harfga o‘tkazing (strtolower), lotin harfi va raqamdan boshqa har qanday belgilar ketma-ketligini bitta _ ga almashtiring, boshidagi va oxiridagi _ ni olib tashlang. Natija bo‘sh bo‘lsa — InvalidArgumentException.
Imzo: function sarlavha_kalit(string $sarlavha): string
Qaytaradi: Kalit satri, masalan narx_som.
sarlavha_kalit('Narx (so‘m)')"narx_som"
Chunking, validatsiya hisoboti va eksport
Xatolardan import hisobotini yig‘ish
<?php $okRows = 7; // model() chaqirilgan qatorlar $failures = [ ['row' => 4, 'field' => 'sku', 'message' => 'SKU band'], ['row' => 4, 'field' => 'narx', 'message' => 'Narx son emas'], ['row' => 9, 'field' => 'birlik', 'message' => 'Birlik noto‘g‘ri'], ]; $failed = count(array_unique(array_column($failures, 'row'))); $report = [ 'total_rows' => $okRows + $failed, 'ok_rows' => $okRows, 'failed_rows' => $failed, ]; echo json_encode($report), PHP_EOL; foreach ($failures as $f) { printf("%d-qator, %s: %s\n", $f['row'], $f['field'], $f['message']); }
{"total_rows":9,"ok_rows":7,"failed_rows":2}
4-qator, sku: SKU band
4-qator, narx: Narx son emas
9-qator, birlik: Birlik noto‘g‘riimport_batches.errors ga yoziladiImport + hisobotni saqlash
public function store(Request $request) { $request->validate(['file' => 'required|file|mimes:xlsx,csv,txt']); $path = $request->file('file')->store('imports'); $import = new ProductsImport(); Excel::import($import, $path); $errors = $import->failures()->map(fn (Failure $f) => [ 'row' => $f->row(), 'field' => $f->attribute(), 'message' => $f->errors()[0], ])->values(); $failed = $errors->pluck('row')->unique()->count(); $batch = ImportBatch::create([ 'file_path' => $path, 'status' => 'done', 'errors' => $errors, 'ok_rows' => $import->okRows, 'failed_rows' => $failed, 'total_rows' => $import->okRows + $failed, 'user_id' => $request->user()->id]); return redirect()->route('imports.show', $batch); }
→ 302 /imports/17 Import #17: 2 312 / 2 340 qator yuklandi, 28 qatorda xato [Xatolarni Excel da yuklab olish]
local diskka — keyin qayta tekshirish uchunFailure obyektlari to‘plami → json hisoboterrors ustuni modelda array cast — json bo‘lib saqlanadiProductsExport — FromQuery
class ProductsExport implements FromQuery, WithHeadings, WithMapping { public function query() { return Product::query()->with('category')->orderBy('sku'); } public function headings(): array { return ['SKU', 'Nomi', 'Kategoriya', 'Birlik', 'Narx (so‘m)']; } public function map($product): array { return [$product->sku, $product->name, $product->category?->name, $product->unit, $product->price]; } }
return Excel::download(new ProductsExport(), 'mahsulotlar.xlsx');
return Excel::download(new ProductsExport(), 'mahsulotlar.csv',
\Maatwebsite\Excel\Excel::CSV);
→ Content-Disposition: attachment; filename=mahsulotlar.xlsxexports.chunk_size) bajariladi — xotira tejaladiButun jadval va bo‘laklab ishlash
✗ Noto‘g‘ri
Product::all()->each(...)— butun jadval xotiradachunk()ichida filtr ustunini o‘zgartirish — yozuvlar o‘tib ketadi- 50 000 qatorni bitta tranzaksiyada yozish
- fayldagi takroriy SKU bilan bitta
upsert— PostgreSQL xatosi
✓ To‘g‘ri
chunkById(1000, ...),lazyById(),cursor()WithChunkReading+WithBatchInsertsimportda- har bir bo‘lak — alohida tranzaksiya, natija hisobotda
- takrorlarni oldindan aniqlab, hisobotga yozish
4-bo‘lim yakuni: Chunking, validatsiya hisoboti va eksport
chunk() emas, chunkById() ishlatiladi?import_batches jadvalida qaysi ustunlar bor va ular nima uchun kerak?FromQuery nima uchun FromCollection dan afzal?Fayllarni saqlash va hujjatlarga biriktirish
Polimorf attachments jadvali
Schema::create('attachments', function (Blueprint $table) { $table->id(); $table->morphs('attachable'); // attachable_type, attachable_id $table->string('disk', 20)->default('local'); $table->string('path'); $table->string('original_name'); $table->string('mime', 100); $table->unsignedBigInteger('size'); $table->foreignId('user_id')->constrained(); $table->timestamps(); });
attachable_type = 'App\Models\Order', attachable_id = 42 path = 'attachments/orders/42/kX3f9aQ...pdf' original_name = 'Buyurtma xati 15-oktabr.pdf'
return $this->morphMany(Attachment::class, 'attachable');return $this->morphTo(); — qaysi hujjatga tegishliHujjatga fayl biriktirish
public function store(Request $request, Order $order) { $this->authorize('update', $order); $request->validate(['file' => ['required', 'file', 'mimes:pdf,jpg,png', 'extensions:pdf,jpg,png', 'max:5120']]); $file = $request->file('file'); $order->attachments()->create([ 'path' => $file->store("attachments/orders/{$order->id}"), 'original_name' => $file->getClientOriginalName(), 'mime' => $file->getMimeType(), 'size' => $file->getSize(), 'user_id' => $request->user()->id, ]); return back()->with('status', 'Fayl biriktirildi'); }
invoice.php (yoki .pdf ga qayta nomlangan PHP) → 422 “file must be a file of type: pdf, jpg, png” skaner.pdf (2,3 MB) → saqlandi: attachments/orders/42/kX3f9aQ....pdf
local disk — vebdan ochiq emasgetClientMimeType() — mijoz aytgani (ishonmang)Ruxsat bilan download va o‘chirish
public function download(Attachment $attachment) { $this->authorize('view', $attachment->attachable); return Storage::disk($attachment->disk) ->download($attachment->path, $attachment->original_name); } public function destroy(Attachment $attachment) { $this->authorize('update', $attachment->attachable); $attachment->delete(); // avval yozuv Storage::disk($attachment->disk)->delete($attachment->path); return back()->with('status', 'Fayl o‘chirildi'); }
GET /attachments/9/download (omborchi, ruxsat yo‘q) → 403 GET /attachments/9/download (menejer) → 200 Content-Disposition: attachment; filename="Buyurtma xati 15-oktabr.pdf"
5-bo‘lim yakuni: Fayllarni saqlash va hujjatlarga biriktirish
local va public disklarining farqi nimada va hujjatlar qayerda saqlanadi?getClientOriginalName() ni saqlash yo‘li sifatida ishlatmaymiz?attachments jadvali qanday muammoni hal qiladi?Oraliq nazorat: loyiha taqdimoti
10 daqiqa: nimani va qanday ko‘rsatamiz
1 daqiqa
2 daqiqa
3–4 daqiqa
/docs, import1 daqiqa
3 daqiqa
Nimaga qaraymiz
| Mezon | Nimani ko‘ramiz | Dalil |
|---|---|---|
| Funksionallik | asosiy oqim ishlaydi, invariantlar buzilmaydi | jonli demo |
| Arxitektura va kod | qatlamlar, servis, Form Request, Resource | repozitoriy, PR |
| Ma’lumotlar | migratsiyalar, cheklovlar, seed | ER-sxema, migrate:fresh --seed |
| Jamoa ishi | vazifalar taqsimoti, kod tahlili | doska, commit tarixi |
| Taqdimot | aniq tushuntirish, savollarga javob | savol-javob |
6-bo‘lim yakuni: Oraliq nazorat: loyiha taqdimoti
Asosiy xulosalar
1Validatsiya chegarada
prepareForValidation → rules → after; controller faqat validated() ni oladi.2Uch qavatli himoya
3Poyga holati
UniqueConstraintViolationException.4Laravel Excel
WithHeadingRow, WithValidation, SkipsOnFailure, WithChunkReading; failures() — hisobot manbai.5Hisobot va eksport
import_batches da natija va xatolar; eksport FromQuery bilan bo‘laklab, CSV uchun BOM.6Fayllar
store() tasodifiy nom, polimorf attachments, yuklab berish faqat authorize() bilan.Yakunlashdan oldin sakkizta savol
prepareForValidation() nima uchun kerak?decimal:0,2 qoidasi nimani tekshiradi?SkipsOnFailure bo‘lmasa nima bo‘ladi?chunkById ?mimes va extensions farqi?8-amaliy mashg‘ulot: 5 ta PHP topshiriq va loyiha bosqichi
Import bo‘laklari (chunk)
Import validatsiya hisoboti
Kontragent qatorini normallashtirish
Upsert rejasi: qo‘shish, yangilash, o‘tkazish
Biriktirma fayl uchun xavfsiz yo‘l
Darsni tark etishdan oldin
Javoblaringizni yozing (✎ Javob yozish) yoki qog‘ozga yozib topshiring.
public diskka va asl nomi bilan saqlamaslik kerak?