Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add ability to set a custom class for the AsCollection and AsEncryptedCollection casts #46619

Merged
merged 11 commits into from
Apr 3, 2023
13 changes: 11 additions & 2 deletions src/Illuminate/Database/Eloquent/Casts/AsCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,15 @@ class AsCollection implements Castable
*/
public static function castUsing(array $arguments)
{
return new class implements CastsAttributes
return new class($arguments) implements CastsAttributes
{
protected $arguments;

public function __construct(array $arguments)
{
$this->arguments = $arguments;
}
osbre marked this conversation as resolved.
Show resolved Hide resolved

public function get($model, $key, $value, $attributes)
{
if (! isset($attributes[$key])) {
Expand All @@ -26,7 +33,9 @@ public function get($model, $key, $value, $attributes)

$data = Json::decode($attributes[$key]);

return is_array($data) ? new Collection($data) : null;
$collectionClass = $this->arguments[0] ?? Collection::class;
osbre marked this conversation as resolved.
Show resolved Hide resolved

return is_array($data) ? new $collectionClass($data) : null;
}

public function set($model, $key, $value, $attributes)
Expand Down
13 changes: 11 additions & 2 deletions src/Illuminate/Database/Eloquent/Casts/AsEncryptedCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,21 @@ class AsEncryptedCollection implements Castable
*/
public static function castUsing(array $arguments)
{
return new class implements CastsAttributes
return new class($arguments) implements CastsAttributes
{
protected $arguments;

public function __construct(array $arguments)
{
$this->arguments = $arguments;
}
osbre marked this conversation as resolved.
Show resolved Hide resolved

public function get($model, $key, $value, $attributes)
{
$collectionClass = $this->arguments[0] ?? Collection::class;
osbre marked this conversation as resolved.
Show resolved Hide resolved

if (isset($attributes[$key])) {
return new Collection(Json::decode(Crypt::decryptString($attributes[$key])));
return new $collectionClass(Json::decode(Crypt::decryptString($attributes[$key])));
}

return null;
Expand Down