Giới thiệu
Dữ liệu là một tài sản quý giá trong hệ thống, việc sao lưu để sử dụng khi cần thiết là vô cùng quan trọng. Bài viết này sẽ hướng dẫn bạn cách tạo một dự án đơn giản để sao lưu dữ liệu hàng ngày bằng Laravel Excel.
Tại sao lựa chọn định dạng Excel?
Lý do để sử dụng định dạng file .csv
hoặc .xlsx
cho việc sao lưu dữ liệu là do yêu cầu của khách hàng. Họ cần có khả năng truy cập và sử dụng các file đó một cách dễ dàng. Việc sao lưu dưới định dạng này sẽ giúp khách hàng thuận tiện hơn trong việc quản lý và sử dụng dữ liệu.
Cài đặt Laravel Excel
Trước hết, bạn cần cài đặt Laravel Excel thông qua composer:
composer require maatwebsite/excel:^3.1
Bạn có thể tham khảo tài liệu chi tiết cài đặt tại Laravel Excel Documentation.
Tạo lớp Exporting collections
Tiếp theo, bạn tạo lớp Export bằng lệnh sau:
php artisan make:export AccountExport
Chỉnh sửa lớp AccountExport
để đồng bộ các dữ liệu cần thiết. Dưới đây là một ví dụ chi tiết:
php
<?php
namespace App\Exports;
use App\Models\Account;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithMapping;
class AccountExport implements FromCollection, WithHeadings, ShouldAutoSize, WithMapping
{
use Exportable;
private $stt;
public function __construct()
{
$this->stt = 0;
}
public function collection(): Collection
{
return Account::query()->select([
'name',
'name_org',
'phone_number',
'email',
'class',
'status',
'created_at'
])->where('deleted_at', null)->get();
}
public function headings(): array
{
return [
'STT',
'Tên',
'Tên tổ chức',
'Số điện thoại',
'Email',
'Lớp',
'Trạng thái',
'Tạo ngày'
];
}
public function map($row): array
{
return [
$this->stt++,
$row->name,
$row->name_org,
$row->phone_number,
$row->email,
$row->class,
$row->status == 1 ? 'Hoạt động' : 'Khóa',
$row->created_at->format('d/m/Y H:i')
];
}
}
Tạo Job để sao lưu dữ liệu
Tạo bảng account_backups
để lưu trữ thông tin về các file sao lưu:
php
Schema::create('account_backups', function (Blueprint $table) {
$table->id();
$table->string('file_name');
$table->timestamps();
});
Tạo Job BackupAccountDataJob
Sử dụng lệnh sau để tạo job:
php artisan make:job BackupAccountDataJob
Chỉnh sửa hàm handle
để thực hiện sao lưu:
php
public function handle()
{
$folder = 'backup/';
$name = 'account-' . now()->format('Y-m-d') . '.csv';
$path = $folder . $name;
Excel::store(new AccountExport(), $path, 'public', \Maatwebsite\Excel\Excel::CSV);
$backupFile = new AccountBackup();
$backupFile->fill([
'file_name' => $name
]);
$backupFile->save();
}
Tạo Command để chạy Job
Bạn cần tạo Command cho Job vừa tạo:
php artisan make:command BackupAccountDataCommand
Chỉnh sửa lớp command như sau:
php
class BackupAccountDataCommand extends Command
{
protected $signature = 'account:backup';
protected $description = 'Backup account data';
public function handle()
{
BackupAccountDataJob::dispatch();
}
}
Lập lịch tự động cho Job
Bạn cần thêm vào hàm schedule
trong Kernel.php
như sau:
$schedule->command('account:backup')->daily();
Cập nhật crontab
để Laravel tự động gọi Job:
* * * * * php /path/to/your/project/artisan schedule:run
Hiển thị danh sách file sao lưu
Cuối cùng, bạn cần tạo route và controller để hiển thị danh sách các file đã sao lưu và cho phép tải về:
php
Route::group(['namespace' => 'App\Http\Controllers', 'prefix' => 'account-backup'], function () {
Route::get('/', 'AccountBackupController@index')->name('account_backup');
Route::get('/download/{id}', 'AccountBackupController@download')->name('account_backup.download');
});
Trong controller, định nghĩa các hàm tương ứng:
php
class AccountBackupController extends Controller
{
public function index()
{
$files = AccountBackup::orderBy('created_at', 'desc')->paginate(15);
return view('account_backup.index', compact('files'));
}
public function download($id)
{
$file = AccountBackup::find($id);
if (!$file) {
return redirect()->route('account_backup')->with('warning', 'File không tìm thấy.');
}
return response()->download(storage_path('app/public/backup/' . $file->file_name));
}
}
Kết luận
Bằng cách thực hiện các bước trên, bạn sẽ có một hệ thống sao lưu dữ liệu tự động hàng ngày bằng Laravel Excel. Bài viết không chỉ giúp bạn nắm vững kiến thức về Laravel mà còn cải thiện khả năng quản lý dữ liệu cho ứng dụng của bạn.
Xem thêm : [Top website rèn luyện thuật toán tốt nhất cho sinh viên]
source: viblo