Laravel创建不接受所有输入数组

时间:2015-10-26 09:41:41

标签: php arrays laravel-5.1

我在我的网站(Laravel 5.1)中创建了添加用户功能,其中管理员帐户可以使用电子邮件创建帐户,密码将发送到该电子邮件。 “添加用户”视图中的表单要求提供名称,电子邮件,权限级别和说明。 create函数应该接受来自该wiew的请求,生成密码,将密码和创建者的ID添加到请求中,根据请求创建数据库条目,然后向该地址发送电子邮件。我目前坚持根据请求创建数据库。这是我的功能:

public function create(Request $request)
    {
        //generate password
        $pass = str_random(10);
        $passcrypt = bcrypt($pass);
        $email = $request->input('email');

        //change the fillable in the model
        $user = new User;
        $user->changeFillableMode("CREATE");

        //validation
        $this->validate($request,['fullname'=>'required',
                                  'email'=>'required|email',
                                  'permission_id'=>'required']);


        //adding new items to request array
        $input = $request->all();
        $input = array_add($input,'created_by_user_id',Auth::user()->user_id);
        $input = array_add($input,'password',$passcrypt);


        $user->create($input);


        //send mail
        $data['email'] = $request->input('email');
        $data['pass'] = $pass;

        Mail::queue('mail.mailbodycreate', $data, function($message) use ($email)
        {
            $message->to($email)->subject('Account info');
        });

    }

$ input已经显示密码和创建者ID已经在数组中,但我不断收到错误,因为它不在数组中(因为密码在我的迁移中不可为空)。有人可以帮忙吗?

更新:我在最后一个array_add之后添加dd($input);。这是结果

array:7 [
  "_token" => "9VowN9ICgkAb9cegbbQzhFtfIhmQr0DqlGj724bN"
  "fullname" => "Aldi"
  "email" => "aldi@gmail.com"
  "permission_id" => "1"
  "description" => "testing add user"
  "created_by_user_id" => 4
  "password" => "$2y$10$Dc4TZqMYE1kyPc7wFHBT1.8KUzk35QqV32wKegstjMFHnD/rhjsw6"
]

更新2:这是User表的模型:

    protected $table = 'msuser';

    protected $primaryKey = 'user_id';

    protected $fillable = ['fullname', 'email', 'description','permission_id'];

    protected $hidden = ['password', 'remember_token'];

    protected $dates = ['deleted_at'];

    public function changeFillableMode($mode){
        switch($mode){
            case "CREATE" :
            $this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
            break;
        }
    }

changeFillableMode用于更改控制器函数中$ fillable的内容。

1 个答案:

答案 0 :(得分:1)

我更喜欢以这种方式添加 PHP 中的键值对:

//adding new items to request array
$input = $request->all();
$input['created_by_user_id'] = Auth::user()->user_id;
$input['password'] = $passcrypt;

确保受保护 $ fillable 包含创建

之前所有必需的密钥

使用常量切换

const CREATE = 'create';

public function changeFillableMode($mode){
        switch($mode){
            case self::CREATE:
            $this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
            break;
        }
    }

并称之为:

$user->changeFillableMode(User::CREATE);