ImageColumn default url for stacked columns
Hey đź‘‹ I am trying to create a stacked image column for related model (users). Because user model image is not required I want to set default image url with method that returns full url of user avatar if his img_path field is empty.
I tried with code below but it is not working because the method defaultImageUrl should return the string and not the array value. Does anyone know how I can set default image url for the stacked ImageColumn?
Tables\Columns\ImageColumn::make('users.img_path')
->label('Peoples')
->circular()
->stacked()
->limit()
->limitedRemainingText()
->defaultImageUrl(function ($record) {
$images=[];
foreach($record->users as $user) {
$images[] = $user->getImageUrl();
}
return $images;
}),
Solution:Jump to solution
I think this would be better as an attribute on the model that can return the default image if it doesn’t exist. Then reference that attribute for the column instead of img_path. Then you don’t need to worry about the defaultImageUrl.
10 Replies
Shouldn't it use one default image if it is empty?
That is a good option, but is there any way to display user avatar url? I want to display different avatars based on the user initials.
https://ui-avatars.com/api/?name=John+Doe
I return this string inside the getImageUrl() method but doesn't work if you want to use it on the ImageColumn that also uses stacked() method. It expects string type and not array of strings.
I would probably need something similar to defaultImagesUrls() to return different default image url for each of the stacked images but I didn't find anything similar already existing in docs.
sorry, I didn't understand what you want.
defaultImageUrl
will display a placeholder image if one doesn't exist yet.That's true but I am trying to figure out how to display different placeholder image based on stacked ImageColumn that display multiple images.
For example: The column displays three different images of users in the classroom. One has a profile image, and the other two don't. For those two I want to display an avatar that is the same as their initials.
Solution
I think this would be better as an attribute on the model that can return the default image if it doesn’t exist. Then reference that attribute for the column instead of img_path. Then you don’t need to worry about the defaultImageUrl.
The result would be something like this, right?
As Adam said, you could create an attribute to return an array like that.
I’m saying that by doing it on the model you won’t need the array. Since the users appears to be a relationship in this case. So, each user will return its own image, so it wouldn’t matter if it was one user or 12 no matter where it is called.
Thanks Leanardo & awcodes. This works perfectly.
I added a custom attribute named avatar & defined it in the model $appends array. All images are displayed now.