John Little
John Little

Reputation: 12447

laravel model - how to dynamically set a column value in the Model?

When a User is created, e.g. with the following line in a controller:

$user = $this->create($request->all());

This will insert a user record with the form values (name, email, password etc).

But if we want to set a "hidden" user fields/colums on the model and DB table, e.g. a special unique generated token (user.token), We dont want to do this in every controller.

If laravel had a service layer, it could be done here, but better would be to do it in the model itself.

e.g. by catching a beforeSave callback, and having some code generate the token and set the corresponding field before it gets written to the DB. I see that the model has saved() event/observers, but this looks like it happens after the save, and I dont want to put this logic in an external class, It belongs in the model, and the documenation doesnt say if the observer can modify the model (by setting columns in this case)

Any suggestions?

Upvotes: 0

Views: 2679

Answers (1)

fubar
fubar

Reputation: 17398

It is possible to define event listeners directly within your model. E.g. add a boot method to your User model:

/**
 * Define model event callbacks.
 *
 * @return void
 */
public static function boot()
{
    parent::boot();

    static::saving(function ($model) {
        $model->token = str_random(60);
    });
}

Alternative, more verbose implementation:

/**
 * Define model event callbacks.
 *
 * @return void
 */
public static function boot()
{
    parent::boot();

    static::saving(function ($model) {
        if (method_exists($model, 'beforeSave')) $model->beforeSave();
    });
}

/**
 * Before save event listener.
 *
 * @return void
 */
public function beforeSave()
{
    $this->token = str_random(60);
}

Upvotes: 4

Related Questions