LaravelMySQLPHP

Laravel Eloquent Model Events

Hi All ,

In this post , I’ll talk about Eloquent Model Events.

Looks Like Database Trigger Isn’t it?

When I read the documentation , I said “Mysql already doing this so..”. Personally, still I prefer to use Mysql Triggers for database operations. It’s more faster and guaranteed. But day by day NoSQL solutions or Hybrid database solutions like using MongoDB and Mysql together becoming as a popular solutions.  Also each NoSQL database is different, but MongoDB doesn’t support  actually stored procedures or triggers. In that case , we need to handle this kind of situations.

If you are interested in MySQL-NoSQL Hybrid Solution with Laravel. You can check this package by Jessenger.

For More

Laravel site has a simple usage example for Eloquent Model Events for “Validation”. In real projects , we have to validate every input , when model “updating” and “creating” its very important. So, Model Events is amazingly useful for this job. You can check the JeffreyWay Model Validation package from github.  This package supports model based validation rules.

Generaly, we need to delete photos , avatars , attachments from FTP too or Logging Model actions We can add more usages examples depends on situation. Let’s see abilities of Model Events.

Event Types

  • Creating 
  • Created
  • Updating
  • Updated
  • Saving
  • Saved
  • Deleting 
  • Deleted 
  • Restoring
  • Restored

“Talk is cheap Show me the code”..

Let’s make a little scenario. I have  “Users”  , “Photos” and “Comments” with following Relations.

  • User Has Many Photo
  • User Has Many Comment
  • Photo Has Many Comment

Example 1 :  I want to delete file of Photo from FTP when Model Deleted.

 protected static function boot() {
        parent::boot();
        static::deleted(function(Photo $photo) {
            // Get the Real Photo Path
            $filename = public_path('photos/'.$photo->url);
            if (File::exists($filename)) {
                File::delete($filename);
            } else {
                return false;
            }
        });
    }

 

Example 2 : Let’s say I need to Log all update actions or versioning from Comment Model.

protected static function boot() {
    parent::boot();    
    static::updated(function(Comment $comment){
         Log::info($comment->user_id." updated at ".$comment->updated_at);
         //local.INFO: 1 updated at time
    });
}

You can check the storage/laravel.log file.

 

Example 3 : I want to update Total Photo Comment when new Comment created.

NOTE  : This can be do it by MySQL trigger.

    protected static function boot() {
        parent::boot();
        static::created(function(Comment $comment) {
            //Created Comment
            echo "Created Comment : " . $comment;
            //Total Comment Belongs To Photo
            $total_comment = Photo::find($comment->photo_id)->comments()->count();
            //Print Total Photo
            echo "</br>Total Comment : " . $total_comment;
            //Update total Comment of Photo
            echo "<br> Update Status : " . Photo::where('id', $comment->photo_id)
                    ->update(array('total_comment' => $total_comment));
        });
    }

 

Most useful things in this example Depency Injection. When I call the static::created function. It’s comming with Created “Comment Model”. Now, i’m able to reach functions which is belongs to Comment Model like “photos()”

As a Result Following SQL executed.

insert into `comments` (`text`, `user_id`, `photo_id`, `updated_at`, `created_at`) values ('Test Comment', '1', '9', '2015-02-01 11:32:12', '2015-02-01 11:32:12')

select count(*) as aggregate from `comments` where `comments`.`photo_id` = '9'

update `photos` set `total_comment` = '26', `updated_at` = '2015-02-01 11:32:12' where `id` = '9'

 

Happy Coding..

Muharrem Tığdemir

 

Author

Muharrem Tığdemir

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.