您当前的位置: 首页  >  博文日记

dcat admin批量导入用户,并指定用户角色的方法

作者:总管理员 时间:2023-05-17 07:00:26 阅读数:1003人阅读

先获取全部角色:

 $roleModel = config('admin.database.roles_model');
$roles = $roleModel::all()->pluck('id', 'name')->toArray();

在创建用户后,添加关联:

                            $fh = Administrator::create($ups);
                            if ($role && isset($roles[$role]) && $roles[$role]) {
                                //admin_role_users. role_id. user_id
                                $fh->roles()->sync([$roles[$role]]); //创建用户和角色之间的关联
                            }

详细代码如下:

<?php

namespace App\Admin\Extensions\Renderable;

use Admin;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Widgets\Form; //创建表
use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Support\SheetCollection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;

class ImportForm extends Form
{
    // 增加一个自定义属性保存用户ID
    protected $bm;

    // 构造方法的参数必须设置默认值
    public function __construct($bm = null)
    {
        $this->bm = $bm;
        parent::__construct();
    }

    // 处理请求
    public function handle(array $input)
    {
        if (! Admin::user()->isAdministrator() && ! Admin::user()->isRole('tby')) {
            return $this->response()->error('无权操作!');
        }
        $bm = str_replace(' ', '', $input['bm']);
        $overlay = $input['overlay'] ?? 0; //0为插入,1为覆盖
        $glkg = $input['glkg'] ?? 0; //过滤空格
        if (! Schema::hasTable($bm)) {
            return $this->response()->error('表不存在!');
        }
        if ($overlay == 1 && $bm != 'admin_users') {
            DB::table($bm)->truncate(); //覆盖时先清空
        }
        $file = 'uploads'.DIRECTORY_SEPARATOR.$input['excel']; //上传的文件
        $noinput = []; //因重名未录入的数据
        if (file_exists($file)) {
            $hzm = strtolower(pathinfo($file, PATHINFO_EXTENSION)); //文件后缀
            if ($hzm == 'xlsx') {
                if ($bm == 'admin_users') {
                    $lang = ['用户名' => 'username', '昵称' => 'name', '密码' => 'password', '角色' => 'role'];
                    $roleModel = config('admin.database.roles_model');
                    $roles = $roleModel::all()->pluck('id', 'name')->toArray();
                    $data = Excel::import($file)->first()->toArray();
                    foreach ($data as $value) {
                        if ($glkg == 1) {
                            $username = $value['用户名'] ? str_replace([' ', "\r\n", "\r", "\n"], '', $value['用户名']) : '';
                            $name = $value['昵称'] ? str_replace([' ', "\r\n", "\r", "\n"], '', $value['昵称']) : '';
                            $password = $value['密码'] ? str_replace([' ', "\r\n", "\r", "\n"], '', $value['密码']) : 123456;
                            $role = $value['角色'] ? str_replace([' ', "\r\n", "\r", "\n"], '', $value['角色']) : '';
                        } else {
                            $username = $value['用户名'] ?? '';
                            $name = $value['昵称'] ?? '';
                            $password = $value['密码'] ?? '';
                            $role = $value['角色'] ?? '';
                        }
                        if ($username && $name && $password) {
                            if (Administrator::where('username', $username)->first()) {
                                $noinput[] = $username;

                                continue;
                            }
                            $ups = ['username' => $username, 'name' => $name, 'password' => hash::make($password)];
                            $fh = Administrator::create($ups);
                            if ($role && isset($roles[$role]) && $roles[$role]) {
                                //admin_role_users. role_id. user_id
                                $fh->roles()->sync([$roles[$role]]); //创建用户和角色之间的关联
                            }
                        } else {
                            $noinput[] = $username;
                        }
                    }
                } else {
                    Excel::import($file)->first()->chunk(1000, function (SheetCollection $collection) use ($bm, $glkg) {
                        $data = $collection->toArray();
                        if (count($data) < 1) {
                            return $this->response()->error('表格内容为空');
                        }
                        foreach ($data as $value) {
                            foreach ($value as $key => $val) {
                                if ($glkg == 1) {
                                    $value[$key] = $val ? str_replace([' ', "\r\n", "\r", "\n"], '', $val) : '';
                                } else {
                                    $value[$key] = trim($val);
                                }
                            }
                            $new['created_at'] = now();
                            $new['updated_at'] = now();
                            $news[] = $value;
                        }
                        DB::table($bm)->insert($news);
                    });
                }
            } else {
                return $this->response()->error('表格文件不正确!');
            }
            // $path = public_path($file);
            // if(file_exists($path)){
            //     unlink($path);//上传完删除源文件
            // }
            if ($bm == 'admin_users' && count($noinput) > 0) {
                return $this->response()->alert(true)->warning('以下用户未能导入,请检查')->detail(implode(',', $noinput));
            }
        } else {
            return $this->response()->error('文件上传失败!');
        }

        return $this->response()->success('导入完成!')->refresh();
    }

    public function form()
    {
        $this->hidden('bm')->value($this->bm);
        if ($this->bm != 'admin_users') {
            $this->switch('overlay', '覆盖原数据')->default(0)->help('默认为插入数据,如果要先清空原数据再导入,可将开关打开');
        }
        $this->switch('glkg', '过滤空格换行')->default(0)->help('过滤内容中的空格和换行符');
        $this->file('excel', '上传文件')->disk('admin')->required()->accept('xlsx')->autoUpload()->help('<b style="color:red;">请先下载模板。</b>')->override();
    }
}

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱: 2554509967@qq.com

标签: laravel

需要 登录 才能发表评论
热门评论
0条评论

暂时没有评论!