Laravel模型事件不会激发

时间:2014-11-11 06:40:22

标签: laravel

我的控制器上有这个代码

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');
    });

并且在Laravel.log上我没有看到“日志消息”,模型事件不会触发。我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

在您将模型实际保存为@SamSquanch之前,必须先设置model event。推荐的方法(不包括观察者)是使用boot方法。

在你的情况下,它会是这样的:

<?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();
    } 
}

这将触发模型上的所有保存。如果您只想在成功创建模型时触发,请将static::saved更改为static::created

答案 1 :(得分:0)

您在模型上调用保存后设置事件关闭。在定义事件闭包后,您应该调用save。

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();
}