Laravel accessor not working after I upgraded from v8.75 to v11.31
I had this LARAVEL v8.75 App where in the User model I created an Accessor for photo like below
public function getPhotoAttribute($value)
{
// Default Photo
$defaultPhotoUrl = mediaUrl('assets/user.png');
return !empty($value) && $value != 'undefined' ? (new FileHelper)->getFileUrl($value) : $defaultPhotoUrl;
}
with the intention of setting the user default image where it's null, but after my upgrade to v11.31, I noticed empty photos are returned as null instead of with the default image
I went through the documentation and noticed that the syntax was changed. then I upgraded the function to:
/**
* Interact with the user's photo.
*/
protected function photo(): Attribute
{
return Attribute::make(
get: fn (string $value) => (!empty($value) && $value != 'undefined' ? (new FileHelper)->getFileUrl($value) :mediaUrl('assets/user.png')),
);
}
but yet no result
In Laravel 9+, the old get---Attribute
magic methods still work, but the new Attribute
based accessors have a slightly different signature and behavior.
In your case you have to
use Illuminate\Database\Eloquent\Casts\Attribute;
protected function photo(): Attribute
{
return Attribute::make(
get: function ($value, array $attributes) {
$raw = $attributes['photo'] ?? null;
if (!empty($raw) && $raw !== 'undefined') {
return (new FileHelper)->getFileUrl($raw);
}
return mediaUrl('assets/user.png');
}
);
}