Question

I'm trying to make my Laravel UserController as lean as possible without using any additional packages, like Ardent (I find it unnecessary; overkill.)

This is my postRegister() function, the function that is routed to when the user clicks "submit" on the registration form.

public function postRegister() {
    $validator = new Services\Validators\RUser;
    if ($validator->passes()) {
        User::create(Input::all());
        return Redirect::to('login');
    }
    return Redirect::to('register')->withInput()->withErrors($validator->getErrors());
}

I sent all the input off to be validated in another class, then I just call the class statically with User::create(). I'm wondering if this is safe or not. I'm having everything but the id and password_confirmation mass-assigned, and the password is hashed in a mutator function.

If this isn't a safe way to handle user creation, how else should I do it? Should I instead create an instance of the object and manually assign values? Thanks in advance.

Was it helpful?

Solution

Basically, the Model::Create function does these steps:

  1. Instantiate a new model instance
  2. Using the input array, fill in all unguarded/fillable model attributes using set-mutators if available
  3. Save model to DB
  4. Return model

So as long as you add the fields that you don't want to be mass-assigned to your $guarded array (or excluded them from your $fillable array) there shouldn't be any security risks. The functionality is about the same as building the model gradually and then saving it.

As a recommendation: The input validation should happen within the model during either the "saving" or "creating" event. If you return false during one of those events, you'll halt the model creation.

OTHER TIPS

As long as you populate the models $fillable array with only the values you want mass-assignable this is safe. Validating all the $fillable values then adds the safe-guard you're asking about.

This ensures that only the values in $fillable are ever populated on the model with any other Input disregarded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top