Lời nói đầu
Xin chào các bác! lại là em đây ] Em chắc nhiều bác khi làm dự án đã được yêu cầu import dữ liệu file excel hoặc file csv vào database. Khi đó chúng ta thường sẽ nghĩ ngay đến các hàm xử lý mà php cung cấp sẵn như fopen để đọc file, fgetcsv để đọc file csv ... Tuy nhiên hôm nay em sẽ giới thiệu đến bạn 1 package hỗ trợ chúng ta đọc, xuất file excel hay file csv một cách rất dễ dàng và nhanh chóng. Và đó chính là maatwebsite/excel. Nhưng hôm nay em sẽ không làm import file bình thường mà em tập chung chủ yếu vào việc validate dữ liệu trong file import. Cùng bắt đầu nhé!
Khởi tạo project
đầu tiên thì các bác hãy tạo một project laravel mới
composer create-project --prefer-dist laravel/laravel test_import_csv_file "5.8.*"
Tạo route
Sau khi install xong project thì các bác hãy vào file
use Illuminate\Http\Request;
...
Route::post['/import', function [Request $request] {
return view['welcome'];
}]->name['import.csv'];
1 và thêm như sau:use Illuminate\Http\Request;
...
Route::post['/import', function [Request $request] {
return view['welcome'];
}]->name['import.csv'];
để cho nhanh và thuận tiện thì em sử dụng luôn closure function ở route, không cần mất thời gian tạo controller =]] .
Tạo view blade
Chắc chắn rồi, chúng ta cần một giao diện để thực hiện chức năng import dữ liệu. em tận dụng luôn file welcome.blade.php để thêm form import vào nhé:
DOCTYPE html>
Laravel
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 13px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
@csrf
Submit
Giờ các bác chỉ cần config thêm database là chúng ta có thể bắt đầu thực hiên validate data từ file csv rồi.
Tạo form request
Tất nhiên rồi, để validate data records bên trong csv file thì trước tiên chúng ta cần phải validate file upload lên server trước đúng không nào. Các bác hãy tạo một form request như sau:
php artisan make:request ImportCsvFileRequest
Laravel sẽ tạo ra cho chúng ta file
use Illuminate\Http\Request;
...
Route::post['/import', function [Request $request] {
return view['welcome'];
}]->name['import.csv'];
2 với nội dùng như sau: