Skip to content

Commit 1e6bb82

Browse files
authored
Merge pull request #19 from yabhq/allow-money-nullable
Allow Money cast to be nullable
2 parents 4414f67 + 32630d7 commit 1e6bb82

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

src/Casts/Money.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ class Money implements CastsAttributes
1717
*/
1818
public function get($model, $key, $value, $attributes)
1919
{
20+
if (is_null($value)) {
21+
return $value;
22+
}
2023
return $value * 0.01;
2124
}
2225

@@ -25,7 +28,7 @@ public function get($model, $key, $value, $attributes)
2528
*
2629
* @param \Illuminate\Database\Eloquent\Model $model
2730
* @param string $key
28-
* @param array $value
31+
* @param mixed $value
2932
* @param array $attributes
3033
* @return string
3134
*/

tests/Migrations/2020_06_23_000000_create_castable_models_table.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public function up()
1515
{
1616
Schema::create('castable_models', function (Blueprint $table) {
1717
$table->increments('id');
18-
$table->integer('amount');
18+
$table->integer('amount')->nullable();
1919
$table->timestamps();
2020
});
2121
}

tests/MoneyCastTest.php

+17
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,21 @@ public function monetary_values_are_stored_in_cents_and_retrieved_in_dollars()
2323

2424
$this->assertEquals(39.95, $model->amount);
2525
}
26+
27+
/** @test */
28+
public function money_casted_value_returns_null_if_null_in_database()
29+
{
30+
$model = CastableModel::create([
31+
'amount' => null,
32+
]);
33+
34+
$this->assertDatabaseHas('castable_models', [
35+
'id' => $model->id,
36+
'amount' => null
37+
]);
38+
39+
$model = $model->fresh();
40+
41+
$this->assertNull($model->amount);
42+
}
2643
}

0 commit comments

Comments
 (0)