1

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;

$user->save();

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 $request array which can then be used by the $user->sqltable = $sqltableitem

Something like

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

Is this possible and any other suggestions?

1 Answer 1

2

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);;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Does this also bcyrpt my passwords?
@Albert, I don't know which auth system do you use, but if you need to do that manually, use mutators (check the updated answer).
I did this before the clause and it works perfectly $request['password'] = bcrypt($request['password'] , No need for that other bit. I've edited the question so can you accept it
@Albert, thanks for suggestion, but the right way to do that kind of stuff is to use mutators. You controllers should be tiny and Model related logic should be in a Model.
You're right, I'll try have a shot with the mutators

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.