Albert Albert - 10 months ago 23
PHP Question

Create a variable for each array item

I have the following code for my post sign up page on my site.

$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;


I need to know if it is possible to simplify my code incase I add new sign up options. What I'm trying to do is create a variable for each item in the
array which can then be used by the
$user->sqltable = $sqltableitem

Something like

foreach ($REQUESTITEM?? as $???){

Is this possible and any other suggestions?


You don't need to create a variable for each element. Just use mass assignment feature:

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

One this clause does exactly the same as all your posted code.

Don't forget to fill $fillable array:

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

If you want to bcrypt password manually, the right way to do this will be creating mutator:

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