laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.71k stars 11.06k forks source link

[Bug] Important: Model Events not working correctly #3880

Closed nicknill closed 10 years ago

nicknill commented 10 years ago

Events not fired when relation of model was loaded.

Steps to reproduce:

  1. Create Test and Test2 eloquent model
  2. Add a relation (for example hasMany)
$test = Test::findOrFail(1);
//load relation
$test->test2

$new = new Test;
$new->somevalue = 'amso';

/// IN THIS CASE creating, saving etc events will NOT work
$new->save();

Tested at head of 4.1 branch

nicknill commented 10 years ago

Here is full test file, used in my case.

require 'vendor/autoload.php';

$pdoCfg = \Symfony\Component\Yaml\Yaml::parse(file_get_contents('config/database.yml'));

// Bootstrap Eloquent ORM
$container = new \Illuminate\Container\Container();
$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory($container);
$conn = $connFactory->make($pdoCfg);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);

class Admin extends \Illuminate\Database\Eloquent\Model {
    public $table = 'Admin';
    public $primaryKey = 'Id';
    protected $requiredFields = array('Login','Password');

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

        static::$dispatcher = new \Illuminate\Events\Dispatcher;

        static::saving(function($model){

            if(is_array($model->requiredFields))
                foreach($model->requiredFields as $required) {
                    if(!isset($model->$required) || empty($model->$required))
                        throw new \Exception('Required fields are empty');
                }
        });

    }

    public function ip() {
        return $this->hasMany('IP','AdminId');
    }
}

class IP extends \Illuminate\Database\Eloquent\Model {
    public $table = 'AdminIP';
    public $primaryKey = 'Id';
    protected static function boot() {
        parent::boot();

        static::$dispatcher = new \Illuminate\Events\Dispatcher;

        static::saving(function($model){

            if(is_array($model->requiredFields))
                foreach($model->requiredFields as $required) {
                    if(!isset($model->$required) || empty($model->$required))
                        throw new \Exception('Required fields are empty');
                }
        });
    }

}

$admin = Admin::findOrFail(1);
$admin->ip;

$new = new Admin();

$new->save();

It must throw an exeption, but it just saving empty model

nicknill commented 10 years ago

Oh, found.

Not a bug, static::$dispatcher = new \Illuminate\Events\Dispatcher; calls few times