dwightwatson / validating

Automatically validating Eloquent models for Laravel
MIT License
968 stars 76 forks source link

$model->save() explanation is needed #110

Closed PavelPolyakov closed 9 years ago

PavelPolyakov commented 9 years ago

Hi,

Sorry for asking you here, but in order to get better understanding I want to ask you the next.

In the documentation it's stated that as soon as we use the validationTrait, we can start doing this.

if ( ! $post->save())
{
    // Oops.
    return Redirect::route('posts.create')
        ->withErrors($post->getErrors())
        ->withInput();
}

return Redirect::route('posts.show', $post->id)
    ->withSuccess("Your post was saved successfully.");

But, I don't see any link to the save() method in the trait, and I don't see that we're subscribing on any of the save events in the package.

Could you explain me how this functionality works internally? Why this simple save() method call would call the validation?

You can say I should install the package and debug it, but as this is only the theoretical question, I would be happy if someone would point me to the right direction.

Thanks in advance.

dwightwatson commented 9 years ago

The save method comes from Eloquent. Your model still extends from Eloquent but it also uses the ValidatingTrait.

When Eloquent is booted on a model with traits it looks for static methods with the name of the trait to boot traits as well, see bootValidatingTrait() here. In that method we register an observer with the static::observe method.

The ValidatingObserver has methods which are called when particular Eloquent events are fired, for example saving or deleting. It runs the validation on these events and if validation fails it returns false and prevents the persistence from occurring.

Booting traits and observing Eloquent events are both documented features of the ORM and this package simply uses them together. You might want to take a look at the save() method from Eloquent and see which events it fires, when it fires them and why.

Hope this helps!

PavelPolyakov commented 9 years ago

Thanks, now it's clear!