代码之家  ›  专栏  ›  技术社区  ›  Sasha

Laravel 5.6-雄辩的创建不接受数组

  •  0
  • Sasha  · 技术社区  · 6 年前

    不知为什么 创造 方法将不接受通过的 数组 当我尝试创建新用户时。

    我得到以下错误:

    SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2018-05-30 13:24:33, 2018-05-30 13:24:33))
    

    这是当前代码:

    public function storeUser($data, $request)
        {
            if($request->hasFile('avatar'))
                $data['avatar'] = $this->uploadAvatar($request->file('avatar'));
    
            $password = \Hash::make($data['temp_password']);
    
            $data['password']           = $password;
            $data['temporary_password'] = $password;
            $data['social']             = Strings::arrayToJson($data['social']);
    
            // Assign the clinic_id from the select menu (only super admin have the permission to do this)
            if(\Auth::user()->hasRole('super_admin') && isset($data['clinic_user']))
                $data['clinic_id'] = (int) $data['clinic_user'];
    
            // If the admin of the clinic is creating the user we wiil use his clinic_id for the new user
            if(\Auth::user()->hasRole('admin'))
                $data['clinic_id'] = \Auth::user()->clinic_id;
    
            if($this->create($data)){
    
                event(new NewUser($this, $data['temp_password']));
    
                if(\Auth::user()->hasRole('super_admin') && isset($data['clinic_owner']))
                    event(new ClinicUpdate($this));
    
                if(\Auth::user()->hasRole('super_admin', 'admin') && \Auth::user()->id !== $this->id)
                    $user->giveRole($data['user_role']);
    
                return true;
            }
    
            return false;
    
        }
    

    用户型号:

    <?php
    
    namespace App;
    
    use App\App\Permissions\HasPermissionsTrait;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
        class User extends Authenticatable
        {
            use Notifiable, HasPermissionsTrait;
    
            /**
             * The attributes that are mass assignable.
             *
             * @var array
             */
            protected $fillable = [
                'first_name', 'last_name', 'about', 'education', 'position', 'phone',
                'social', 'title', 'gender', 'avatar', 'location', 'email', 'password',
                'temporary_password', 'verified', 'clinic_id'
            ];
    
            /**
             * The attributes that should be hidden for arrays.
             *
             * @var array
             */
            protected $hidden = [
                'password', 'remember_token',
            ];
    
            public function clinic()
            {
               return $this->belongsTo(Clinic::class);
            }
    
            public function files()
            {
               return $this->hasMany('App/Media');
            }
    
            public function verifyUser()
            {
                return $this->hasOne('App\VerifyUser');
            }
    
        }
    

    用户创建请求:

    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Validation\Rule;
    
    class UserCreateRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            $rules = [];
    
            if(\Auth::user()->hasRole('super_admin', 'admin'))
                $rules = [
                    'user_role'    => [Rule::in(['super_admin', 'admin', 'user'])],
                    'clinic_owner' => 'integer',
                    'clinic_user'  => 'integer',
                ];
    
            return array_merge($rules, [
                'first_name'    => 'required|string|max:255',
                'last_name'     => 'required|string|max:255',
                'email'         => "required|string|email|unique:users",
                'temp_password' => 'required|string|min:8',
                'title'         => 'integer',
                'gender'        => [Rule::in([0, 1])],
                'position'      => 'string|max:255|nullable',
                'phone'         => 'string|max:255|nullable',
                'location'      => 'string|max:255|nullable',
                'about'         => 'string|nullable',
                'social.*'      => 'url|nullable',
                'avatar'        => 'nullable|image|mimes:jpeg,jpg,png,gif',
            ]);
        }
    
        public function attributes()
        {
            return [
                'social.facebook'  => 'Facebook',
                'social.twitter'   => 'Twitter',
                'social.instagram' => 'Instagram',
                'social.linkedin'  => 'Linkedin',
                'temp_password'    => 'Temporary Password',
            ];
        }
    }
    

    新用户事件:

    <?php
    
    namespace App\Events;
    
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    
    class NewUser
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public $_user;
        public $_tempPass;
    
        /**
         * Create a new event instance.
         *
         * @return void
         */
        public function __construct($user, $tempPass)
        {
            $this->_user     = $user;
            $this->_tempPass = $tempPass;
        }
    
        /**
         * Get the channels the event should broadcast on.
         *
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn()
        {
            return [];
        }
    }
    

    用户控制器(存储方法):

    public function store(UserCreateRequest $request)
        {
            $validated = $request->validated();
    
            $model = new UserQuery;
    
            if(!$model->storeUser(XSS::clean($validated, ['avatar']), $request)){
    
                Session::flash('alert', [
                    'message' => 'Something went wrong. Please try again',
                    'type'    => 'danger'
                ]);
    
                return \Redirect::back();
            }
    
            return redirect('/admin/users');
    
        }
    

    这是 DD 对于数据:

    array:17 [▼
      "user_role" => "admin"
      "clinic_user" => "1"
      "first_name" => "Sasha"
      "last_name" => "Miljkovic"
      "email" => "xxxxxx@xxxxx.com"
      "temp_password" => "12345678"
      "title" => "10"
      "gender" => "0"
      "position" => "Tester"
      "phone" => "1234"
      "location" => "Pirot"
      "about" => "Maecenas gravida tellus augue, sed mollis quam viverra at. Aenean sit amet dui non eros laoreet porta et nec nisi. Cras lectus justo, porttitor quis mattis nec, ▶"
      "social" => "[]"
      "avatar" => "avatar_5b0ea46d2af8d.jpg"
      "password" => "$2y$10$gxGPBbwS44KHXLn57leRpukX/zu/rX3SSn7jRdM27kvQb9N84CcGa"
      "temporary_password" => "$2y$10$gxGPBbwS44KHXLn57leRpukX/zu/rX3SSn7jRdM27kvQb9N84CcGa"
      "clinic_id" => 1
    ]
    
    2 回复  |  直到 6 年前
        1
  •  -1
  •   ali    6 年前

    必须传递所有必需的文件

    $data['first_name'] = 'some name';
    

    该错误告诉您“名字”字段不通过,您必须通过该字段,并且需要其他字段才能防止此错误

        2
  •  1
  •   Zakaria Acharki    6 年前

    你应该实例化 User 相反,请尝试:

    (new User())->create($data)
    

    如果有效,则更换:

    $model = new UserQuery;
    

    通过:

    $model = new User;