为每个数组项创建一个变量

时间:2016-05-11 13:21:39

标签: php laravel

我的网站上的帖子注册页面有以下代码。

df1 <- data.frame(Year = 1843, Month = 1, Day = c(1, 5, 7, 10), Rainfall= c(4.3, 0, 1.1, 0))
Dates <- seq(as.Date("1843-01-01"), as.Date("1843-01-10"), by = "1 day")
data_frame(Dates) %>%
   separate(., Dates, into = c("Year", "Month", "Day"), convert=TRUE) %>%
   left_join(., df1, by = c("Year", "Month", "Day"))
#   Year Month   Day Rainfall
#   <dbl> <dbl> <dbl>    <dbl>
#1   1843     1     1      4.3
#2   1843     1     2       NA
#3   1843     1     3       NA
#4   1843     1     4       NA
#5   1843     1     5      0.0
#6   1843     1     6       NA
#7   1843     1     7      1.1
#8   1843     1     8       NA
#9   1843     1     9       NA
#10  1843     1    10      0.0

我需要知道是否可以简化我的代码,因为我添加了新的注册选项。我要做的是为$email = $request['email']; $username = $request['username']; $password = bcrypt($request['password']); $mmail = $request['mmail']; $terms = $request['terms']; $user = new User(); $user->email = $email; $user->username = $username; $user->password = $password; $user->mmail = $mmail; $user->terms = $terms; $user->save(); 数组中的每个项创建一个变量,然后由$request

使用

这样的东西
$user->sqltable = $sqltableitem

这可能吗?还有其他建议吗?

1 个答案:

答案 0 :(得分:2)

您无需为每个元素创建变量。只需使用mass assignment功能:

$user = User::create($request->all());

一个this子句与您发布的所有代码完全相同。

不要忘记填充$fillable数组:

class User extends Model
{
    protected $fillable = ['email', 'username', 'password', 'mmail', 'terms'];
}

如果您想手动设置bcrypt密码,正确的方法是creating mutator

class User extends Model
{
    public function set setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);;
    }
}