rgvcorley
rgvcorley

Reputation: 2933

Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM

The Problem

I would like to automatically add created_by and modified_by fields to every insert/update to a database table in Laravel 4, regardless of whether I am using Eloquent or Query Builder. However, not all my tables have these fields so any solution will have to check these columns exist before adding.

Attempted Solution

I have extended the Illuminate\Database\Eloquent\Model class and written an overwrite method save() in order to add some additional meta data fields for every record that is saved.

This is fine except that if I perform an insert using the Query Builder then this is bypassed. Looking at the Model class it appears that the database operations are actually done using the query builder.

I have had a look at the Illuminate\Database\Query\Builder model and it looks like I could probably write overwrite methods for insert() and update().

Is this a sensible way to go about performing some task for every insert/update or will I run into trouble later down the line?

Upvotes: 10

Views: 22446

Answers (5)

ruwan800
ruwan800

Reputation: 1885

In Laravel if you like to call a single method on each save/update from a single point without making any additional changes in each of the extended Models, you can have a custom listener for eloquent events. As documetation says it can be done only for per Model. But creating a custom listener allows to access any event in any Model.

Just add a listener to the boot() method in EventServiceProvider like below and modify accordingly.

Event::listen(['eloquent.saving: *', 'eloquent.creating: *'], function($event){
        //your method content
        //returning false will cancel saving the model
 });

Please note that wildcard used to match any model. See documentation for more on events.

Upvotes: 5

fico7489
fico7489

Reputation: 8560

You can use venturecraft revisionable package because in a table from this package all info that you need is already stored, you just need this package to get them in an elegant way : https://github.com/fico7489/laravel-revisionable-upgrade

Upvotes: 0

Mohamed Azher
Mohamed Azher

Reputation: 411

Adding to the above answers. You could do something like this.

Create a class in app/models called BaseModel.php extending \Eloquent

class BaseModel extends \Eloquent{

public static function boot()
{
    parent::boot();

    static::creating(function($model)
    {
        //change to Auth::user() if you are using the default auth provider
        $user = Confide::user();
        $model->created_by = $user->id;
        $model->updated_by = $user->id;
    });

    static::updating(function($model)
    {
        //change to Auth::user() if you are using the default auth provider
        $user = Confide::user();
        $model->updated_by = $user->id;
    });
  }

}

Then in your individual model classes you need to extent the BaseModel instead of \Eloquent

class Product extends BaseModel {

    protected $table = 'product';

    //Booting the base model to add created_by and updated_by to all tables
    public static function boot()
    {
        parent::boot();
    }

}

Now any time you save or update a model, the created_by and updated_by fields would be updated automatically.

Note: This would only work when save or update is done through Eloquent. For query builder, you could have a common method to fetch and append the created_by and update_by column updates.

Upvotes: 12

Ben
Ben

Reputation: 270

If you want to use Query Builder, and Eloquent the only way around this without extending the Core Components (which I don't deem necessary), you can just use the Event System.

Link: http://laravel.com/docs/events

So you'd use an event such as user.custom.save, then create a function for use with the query builder which at the end would trigger this event, same as with Eloquent.

Example:

class User extends Eloquent
{
    public function save()
    {
        Event::fire('user.custom.save', array($this));
        parent::save();
    }
}

Upvotes: 2

Atrakeur
Atrakeur

Reputation: 4244

You must never override the save method to override and add your functionnality.

You have to use the Model Events functionnality that eloquent provides to do that instead.

To put it simply, you have to define a saving event for you model to override/set/check data that the model is going to save.

A simple example to put in a User model class:

//Executed when loading model
public static function boot()
{
     parent::boot();

     User::creating(function($user){
         $user->value1 = $user->value2 +1;
     });
}

More information: http://four.laravel.com/docs/eloquent#model-events

Upvotes: 7

Related Questions