Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Image for Uploading a File?

How can I set a default banner image in the file uploader?

I'm using Laravel's Filament FileUpload component, and I want to display a default banner image when the page loads. If the user uploads a new image, it should replace the default. However, if no image is uploaded, the default banner image should remain.

I've tried using the default() method and the formatStateUsing() function, but neither seems to work:

Forms\Components\FileUpload::make('banner')
    ->disk('banner')
    ->directory('banner')
    ->image()
    ->imageEditor()
    ->maxSize(3072) // 3MB limit
    ->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
    ->formatStateUsing(fn($state) => $state ?? ['banner/banner.png']) // Default banner image
    ->validationMessages([
        'banner.dimensions' => __('validationBannerDimensions'),
        'banner.max' => __('validationBannerMax'),
    ])
    ->rules([
        'dimensions:min_width=500,min_height=500,max_width=1000,max_height=1000'
    ])
    ->helperText(__('validationBannerHelperMsg')),

How to set the default image so that it appears when the form loads?

like image 769
Nik Patel Avatar asked Nov 21 '25 21:11

Nik Patel


1 Answers

Below is the code and link from Livewire documentation. You can adjust the @if ($photo) and add @else to show default image.

ref

<form wire:submit="save">
    @if ($photo) 
        <img src="{{ $photo->temporaryUrl() }}">
    @endif
 
    <input type="file" wire:model="photo">
 
    @error('photo') <span class="error">{{ $message }}</span> > @enderror
 
    <button type="submit">Save photo</button>
</form>

In Filament try using a string not an array for the default banner image:

->formatStateUsing(fn($state) => $state ?: 'banner/banner.png')

You could also try using files :

->files(fn($state) => $state ? [asset('storage/' . $state)] : [asset('storage/banner/banner.png')])

Chat gpt also mentiones that :

"No, using files() alone will NOT store the default image in the database. How files() Works: files() only preloads the image in FilePond for the user to see. It does NOT change the actual saved value in the database. If the user does not upload a new image, the database field will remain null or empty. Will the Default Image Be Saved in the Database? ❌ No, unless you explicitly store it using formatStateUsing() or default(). "

I hope this helps.

like image 121
tvv3 Avatar answered Nov 24 '25 12:11

tvv3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!