RollRodrig
RollRodrig

Reputation: 25

Laravel Model Events dont fire

I have this code on my controller

public function gracias()    
{            
    $client = new Client;
    $client->name = "name";
    $client->lastname = "lastname";
    $client->email = "email";
    $client->phone = "phone";
    $client->save();     

    Client::saved(function($client)
    {
        Log::info('on saved');

        if ($client->isValid())
        {
            Log::info('SUCCESSFULL SAVING MODEL');
        }else
        {
            Log::info('ERROR ON SAVING CLIENT');
        }

    });
    Event::listen('client.create', function($client)
    {
        Log::info('event listen client.create');
    });

and on Laravel.log I don't see the "Logs messages", the Model Events don't fire. What I'm doing wrong?

Thank you!!

Upvotes: 1

Views: 1408

Answers (2)

nickcoffey
nickcoffey

Reputation: 211

You are setting the event closure AFTER you are calling save on the model. You should be calling save after you define the event closure.

public function gracias()
{
    $client = new Client;
    $client->name = "name";
    $client->lastname = "lastname";
    $client->email = "email";
    $client->phone = "phone";

    Client::saved(function($client) {
        Log::info('on saved');

        if ($client->isValid()) {
            Log::info('SUCCESSFULL SAVING MODEL');
        } else {
            Log::info('ERROR ON SAVING CLIENT');
        }

    });

    Event::listen('client.create', function($client) {
        Log::info('event listen client.create');
    });

    $client->save();
} 

Upvotes: 0

Marwelln
Marwelln

Reputation: 29433

A model event must be set before you actually save your models as @SamSquanch mentioned. The recommended way (not including observers) is to use the boot method.

In your case it would be like this:

<?php
class Client extends Eloquent {
    public static function boot() {
        parent::boot();

        static::saved(function($client) {
            Log::info('on saved');

            if ($client->isValid()) {
                Log::info('SUCCESSFULL SAVING MODEL');
            } else {
                Log::info('ERROR ON SAVING CLIENT');
            }

        })
    }

    public function gracias()
    {
        Event::listen('client.create', function($client) {
            Log::info('event listen client.create');
        });

        $client = new Client;
        $client->name = "name";
        $client->lastname = "lastname";
        $client->email = "email";
        $client->phone = "phone";
        $client->save();
    } 
}

This will trigger on all saves on the model. If you only want to trigger when a model have been successfully created, change static::saved to static::created.

Upvotes: 2

Related Questions