当前位置: 首页 > 工具软件 > laravel-menu > 使用案例 >

基于laravel-admin的数据导入

姚宪
2023-12-01

环境

框架/插件版本
laravel6.20
encore/laravel-admin1.8.11

框架搭建 laravel-admin文档

以下讨论均是对设备表Devices,结构为(id, name, device_sn, model_number) orm模型文件 app/Model/Device.php

步骤

一、添加导入Action
php artisan admin:action Imports\ImportDevice --name="导入数据"
  • 生成的类文件 app/Admin/Actions/Imports/ImportDevice.php:
<?php

namespace App\Admin\Actions\Imports;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class ImportDevice extends Action
{
    protected $selector = '.import-device';

    public function handle(Request $request)
    {
        // $request ...
        
        return $this->response()->success('Success message...')->refresh();
    }

    public function html()
    {
       return <<<HTML
        <a class="btn btn-sm btn-default import-tenant">导入数据</a>
HTML;
    }
}

二、安装插件
composer require maatwebsite/excel
  • 添加导入类
php artisan make:import DeviceImport --model=Model\Device
  • 生成的类文件app/Imports/DeviceImport.php:
<?php

namespace App\Imports;

use App\Model\Device;
use Maatwebsite\Excel\Concerns\ToModel;

class DeviceImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new Device([
            //
        ]);
    }

}

  • 修改文件
<?php

namespace App\Imports;

use App\Model\Device;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class DeviceImport implements ToModel, WithStartRow, WithValidation
{
    use Importable;
    use SkipsFailures;

    /**
     * @param array $row
     *	
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        //按照excel单元格顺序定义需要的字段
        return new Device([
            'name' => $row[0],
            'device_sn' => $row[1],
            'model_number' => $row[2],
        ]);
    }
	//从第几行开始,防止读取表头标题
    public function startRow(): int
    {
        return 2;
    }
	
    //添加验证规则
    public function rules(): array
    {
        return [
            '0' => 'required',
            '1' => 'required',
            '2' => 'required',
            '3' => 'required',
        ];
    }

    // 自定义验证信息
    public function customValidationMessages()
    {
        return [
            '0.required' => '设备名必填',
            '1.required' => '设备编号必填',
            '2.required' => '设备型号必填',
        ];
    }

}

三、修改导入action
<?php

namespace App\Admin\Actions\Imports;

use App\Imports\DeviceImport;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class ImportDevice extends Action
{
    protected $selector = '.import-device';

    public function handle(Request $request)
    {
        $import = new DeviceImport();
        $import->import($request->file('file'));
        $str = "";
        foreach ($import->failures() as $failure) {
            $str .= ' 第' . $failure->row() . '行 失败原因:' . implode(' ', $failure->errors()) . '<br> 行数据:' . implode(' ', $failure->values()) . '<br>';
        }
        if ($str !== '') {
            return $this->response()->error($str)->topFullWidth()->timeout(7000000);
        }
        return $this->response()->success('数据导入成功')->refresh();
    }
	
    //文件操作
    public function form()
    {
        $this->file('file', '请选择文件');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-device"><i class="fa fa-upload"></i>导入数据</a>
HTML;
    }
}

四、添加导入按钮
<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Imports\ImportDevice;
use App\Model\Device;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class DeviceController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '设备';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Device());
        //...
        
        //在工具栏添加导入按钮
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportDevice());
        });

        return $grid;
    }
}
 类似资料: