Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Certain CRUD Operations on Laravel Eloquent Models

Is there an easy way to prevent certain CRUD operations from being performed on an Eloquent model?

How I'm doing it now (from memory, I think I'm missing an argument to be compatible with Eloquent's save(), but that's not important):

<?php

class Foo extends Eloquent {

    public function save()
    {
        // Prevent Foo from being updated.
        if (!empty($this->id)) {
            throw new \Exception('Update functionality is not allowed.');
        }

        parent::save();
    }

}

In this case, these models should not be allowed to be updated under any circumstance, and I want my app to explode should something try to update them. Is there a cleaner way to do this without overriding Eloquent's save() method?

like image 915
Jim D Avatar asked Jan 28 '15 22:01

Jim D


2 Answers

In addition to @AlanStorm's answer, here's a comprehensive info:

  1. You can setup global listener for all the models:

    Event::listen('eloquent.saving: *', function ($model) {
      return false;
    });
    
  2. Or for given model:

    Event::listen('eloquent.saving: User', function ($user) {
      return false;
    });
    // or
    User::saving(function ($user) {
      return false;
    });
    
    // If it's not global, but for single model, then I would place it in boot():
    // SomeModel
    public static function boot()
    {
       parent::boot();
    
       static::saving(function ($someModel) {
          return false;
       });
    }
    
  3. For read-only model you need just one saving event listener returning false, then all: Model::create, $model->save(), $model->update() will be rejected.

  4. 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.

like image 115
Jarek Tkaczyk Avatar answered Oct 31 '22 18:10

Jarek Tkaczyk


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

  1. Listening for the creating, updating, saving, or deleting events

  2. Returning false from your event callback.

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

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

in your app/start/global.php file would do the job.

like image 22
Alan Storm Avatar answered Oct 31 '22 19:10

Alan Storm