diff --git a/Translatable/Translatable.php b/Translatable/Translatable.php index e1e97f4b..578db305 100644 --- a/Translatable/Translatable.php +++ b/Translatable/Translatable.php @@ -105,18 +105,31 @@ public function setAttribute($key, $value) public function save(array $options = array()) { - if (count($this->getDirty()) > 0) + if ($this->exists) { - if (parent::save($options)) + if (count($this->getDirty()) > 0) { + // If $this->exists and dirty, parent::save() has to return true. If not, + // an error has occurred. Therefore we shouldn't save the translations. + if (parent::save($options)) + { + return $this->saveTranslations(); + } + return false; + } + else + { + // If $this->exists and not dirty, parent::save() skips saving and returns + // false. So we have to save the translations return $this->saveTranslations(); } - return false; } - else + elseif (parent::save($options)) { + // We save the translations only if the instance is saved in the database. return $this->saveTranslations(); } + return false; } public function fill(array $attributes) diff --git a/tests/TestCoreModelExtension.php b/tests/TestCoreModelExtension.php index c52bff0f..2da79482 100644 --- a/tests/TestCoreModelExtension.php +++ b/tests/TestCoreModelExtension.php @@ -1,11 +1,13 @@ assertGreaterThan(2, count($countries)); $this->assertEquals(2, $this->queriesCount); } + + /** + * @test + */ + public function it_saves_empty_instances() + { + $company = new Company; + $company->save(); + $this->assertGreaterThan(0, $company->id); + + $country = new Continent; + $country->save(); + $this->assertGreaterThan(0, $country->id); + } } \ No newline at end of file diff --git a/tests/migrations/2013_11_28_152610_create_tables.php b/tests/migrations/2013_11_28_152610_create_tables.php index 20da4fa7..0444b43b 100644 --- a/tests/migrations/2013_11_28_152610_create_tables.php +++ b/tests/migrations/2013_11_28_152610_create_tables.php @@ -51,6 +51,28 @@ public function up() $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade'); }); + Schema::create('companies', function(Blueprint $table) + { + $table->increments('id'); + $table->string('name')->nullable(); + $table->timestamps(); + }); + + Schema::create('continents', function(Blueprint $table) + { + $table->increments('id'); + $table->timestamps(); + }); + + Schema::create('continent_translations', function(Blueprint $table) + { + $table->increments('id'); + $table->integer('continent_id')->unsigned(); + $table->string('name'); + $table->string('locale')->index(); + $table->timestamps(); + }); + } diff --git a/tests/models/Company.php b/tests/models/Company.php new file mode 100644 index 00000000..e2ad2a69 --- /dev/null +++ b/tests/models/Company.php @@ -0,0 +1,8 @@ +