Skip to content

Commit

Permalink
Fix return type of jsonSerialize and add toString on models
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Nov 11, 2024
1 parent 4b9a528 commit f1a3eaa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use JsonException;
use Stringable;

abstract class Model implements Arrayable, ArrayAccess, Jsonable, UrlRoutable
abstract class Model implements Arrayable, ArrayAccess, Jsonable, Stringable, UrlRoutable
{
use Bootable;
use ForwardsCalls;
Expand Down Expand Up @@ -583,11 +584,19 @@ public function toJson(mixed $options = 0): string
/**
* Convert the object into something JSON serializable.
*/
public function jsonSerialize(): mixed
public function jsonSerialize(): array
{
return $this->toArray();
}

/**
* Convert the model to its string representation.
*/
public function __toString(): string
{
return $this->toJson();
}

/**
* Dynamically retrieve attributes on the model.
*/
Expand Down
8 changes: 8 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,11 @@

expect($model->toJson())->toBe(json_encode($model->toArray()));
});

it('can be converted to string', function () {
$model = ModelStub::create([
'name' => 'John Doe',
]);

expect((string) $model)->toBe(json_encode($model->toArray()));
});

0 comments on commit f1a3eaa

Please sign in to comment.