Perform action before saving?

2

I'm getting the requests of the form and putting it all at once to save it using Laravel% co

I'm getting this way:

public function save(Request $request)
{
   $user = new User( $request->all() );
   $user->save();
}

The protected $fillable = ['nome', 'idade', 'cep', 'nr_casa']; typed in cep is like this: 69.084-120 and I would like you to save it before it was 69084120 .

Is there any function input in Laravel as well as Yii ?

My table is

nome varchar(100)
idade int
cep varchar(8)
nr_casa varchar(10)
    
asked by anonymous 22.11.2018 / 14:03

2 answers

2

If there is an event part that is made up of a class that generates some or some modifications before the event, eg save, in your code example, a creating can be used so that before creating this record there is some Example :

Create a class in the app\Observers folder that will represent those changes:

class UserObserve 
{
    public function creating(User $user) // somente na hora da criação
    {
        $user->cep = str_replace(['.','-'],'',$user->cep);
    }
    // OU
    // talvez no seu caso o evento é saving porque
    // nesse caso é antes de salvar qualquer modificação
    public function saving(User $user)
    {
        $user->cep = str_replace(['.','-'],'',$user->cep);          
    }
}

Note: I made two methods, you can use one another, one means when creating this record ( creating ) and the other every time before saving (% w / w). There is even more: saving , retrieved , creating , created , updating , updated , saving , saved , deleting , deleted and restoring .

In% w_that is in the restored folder, add the following code snippet in the AppServiceProvider method:

class AppServiceProvider extends ServiceProvider
{

    public function boot()
    {
        User::observe(UserObserve::class);
    }

    public function register()
    {
    }
}

Another example:

22.11.2018 / 14:28
1

The laravel already has a structure already planned for this in the models, are the mutators: link in this case, you can use:

public function setCepAttribute($value) {
    $this->attributes['cep'] = str_replace(['.','-'],['',''],($value);
}

In the same way you can also put dots and dashes back by fetching the value by creating the function

public function getCepAttribute($value) {
   return TRATAR O VALOR AQUI.
}
    
22.11.2018 / 14:48