Prevent updating Eloquent Model

September 21, 2019

by Yunus Shaikh

Prevent certain CRUD operations from being performed on an Eloquent model

wanted To prevent updating the eloquent model ? Below snippet will prevent updating the eloquent model.


    class User extends Eloquent
{
  protected static function boot()
  {
    parent::boot();
    static::updating(function($model)
    {
      return false;
    });
  }
}
This code will prevent updating user.

Eloquent's event system allows you to cancel a write operation by

  • Listening for the creating, updating, saving, or deleting events
  • Returning false from your event callback.

For example, to prevent people from creating new model objects, something like this


        Blog::creating(function($foo)
        {
            return false; //no one gets to create anything
        });
    

Here's the list of all Eloquent events: booting, booted, creating, created, saving, saved, updating, updated, deleting, deleted and also restoring and restored provided by SoftDeletingTrait.

Featured Posts