Replies: 3 comments
-
Where does salutation come from? Is it an attribute of your model? If so, you get the array of values as a parameter in your closure. Also, you could try out $hidden |
Beta Was this translation helpful? Give feedback.
-
The salutation is irrelevant, the point is that a model could have arbitrary methods that might return an Attribute. In my case I use a trait for a "generic" attribute that several models use to return specifics. Let me show you the use case: trait HasImage
{
public function imageUrl(string $property, string $disk = 'public')
{
return Attribute::get(function () use ($property, $disk) {
return Storage::disk($disk)->url($this->$property) ?: null;
});
}
}
class Profile extends Model
{
use HasImage;
protected $fillable = [
'cover_photo_path',
'profile_photo_path',
];
protected $appends = [
'cover_photo_url',
'profile_photo_url',
];
public function coverPhotoUrl(): Attribute
{
return $this->imageUrl('cover_photo_path');
}
public function profilePhotoUrl(): Attribute
{
return $this->imageUrl('profile_photo_path');
}
} In this case |
Beta Was this translation helpful? Give feedback.
-
The salutation was extremely relevant, as it helped me to understand what you were trying to solve and helped you to explain better what those arbitrary reasons are. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When an Eloquent model is cast to array using the $model->toArray() method, all the mutated attributes are found and invoked using Reflection. But the reflection invokes all these methods without parameters, which can cause issues if the model has any custom methods that for any arbitrary reason return an Attribute.
Example of a regular attribute method:
Example of a custom method that returns an Attribute:
The second method will cause the framework to throw an exception because it tries to invoke the method without any parameters.
Since the framework expects the mutated attributes to always be invoked without parameters, I propose adding an extra check to the logic of the function in: https://github.com/laravel/framework/blob/10.x/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L2227
Before:
After:
A workaround is to simply remove the return type from the custom method, but it doesn't feel right.
I can provide code for my specific use case if need be.
Beta Was this translation helpful? Give feedback.
All reactions