Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
rgvcorley Avatar asked Aug 23 '13 08:08

rgvcorley


People also ask

How to update query without use model in Laravel eloquent?

The laravel eloquent provides many types of eloquent methods. so we can easily update data into the database using the Update Query eloquent method. Laravel Update Query Without Use Model In this step, we load the DB and pass the table name and data into the update method. so we can directly pass data without a model. see following below example.

What is the use of query builder in Laravel?

In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates etc and it works on all supported database systems like a champ.

What makes Laravel an awesome framework to learn?

Few tools that make Laravel an awesome framework is the inclusion of “Query Builder and Eloquent ORM”. Through this blog I intend to share few quick pointers on these concepts. In Laravel the database query builder provides an easy interface to create and run database queries.

What is the Laravel eloquent Orm?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.


2 Answers

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(){
        //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.

like image 127
ruwan800 Avatar answered Sep 20 '22 11:09

ruwan800


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.

like image 39
Mohamed Azher Avatar answered Sep 23 '22 11:09

Mohamed Azher