0

Estoy utilizando Laravel, con la libreria Filament. Hice un upload de imagenes, las mismas se guardan en la carpeta correspondiente de storage, pero al momento de guardar los datos en la tabla, donde van las url de las imágenes, solo se guardan datos al momento de subir las imagenes desde la pantalla de editar y no desde la pantalla de crear. En ambos casos la imagen queda alojada en la carpeta local, pero el empacto en la BD solo se da al editar un elemento ya generado.

Comparto los codigos: Venueresource.php

    <?php

namespace App\Filament\Resources;

use App\Filament\Resources\VenueResource\Pages;
use App\Filament\Resources\VenueResource\RelationManagers;
use App\Models\Venue;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Columns\ImageColumn;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Forms\Components\Hidden;
 

class VenueResource extends Resource
{
    protected static ?string $model = Venue::class;
    

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('address')
                ->label('Address:')
                ->required()
                ->extraAttributes(['id' => 'autocomplete']),
                Forms\Components\TextInput::make('zip')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('city')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('state')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('country')
                ->required()
                ->maxLength(255),
                
                Hidden::make('lt')
                ->required(),
                
                Hidden::make('lg')
                ->required(),

                Map::make('location')
                ->mapControls([
                    'mapTypeControl'    => false,
                    'scaleControl'      => true,
                    'streetViewControl' => false,
                    'rotateControl'     => false,
                    'fullscreenControl' => true,
                    'searchBoxControl'  => false, 
                    'zoomControl'       => true,
                ])
                ->reactive()
                ->afterStateUpdated(function ($state, callable $get, callable $set) {
                    $set('lt', $state['lat']);
                    $set('lg', $state['lng']);
                })
                ->autocomplete(
                    fieldName: 'address',
                    placeField: 'name',
                )
                ->defaultLocation([39.526610, -107.727261])
                ->autocompleteReverse(true) 
                ->reverseGeocode([
                    'city' => '%L',
                    'state' => '%A1',
                    'country'=> '%c',
                    'zip' => '%z',
                ]),

                Forms\Components\TextInput::make('region')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('socials')
                ->required()
                ->maxLength(255),
                Forms\Components\TextInput::make('website')
                ->required()
                ->maxLength(255),

                Forms\Components\FileUpload::make('photos')
                ->label('Photosssss')
                ->disk('public')
                ->multiple() 
                ->image() 
                ->directory('venue_photos')
                ->required(),

                Forms\Components\TextInput::make('description')
                    ->maxLength(255),
                Forms\Components\Select::make('created_by')
                    ->label('Created By')
                    ->required()
                    ->relationship('createdBy', 'name') // relationship to the User model
                    ->searchable() // alows searching
                    ->placeholder('Select a user'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable(),
                Tables\Columns\TextColumn::make('address')
                    ->searchable(),
                Tables\Columns\TextColumn::make('description')
                    ->searchable()
                    ->formatStateUsing(function ($state) {
                        return \Str::limit($state, 35, '...'); // Limit a string to a maximum of  10 characters
                    }),
                Tables\Columns\TextColumn::make('createdBy.name')
                    ->label('Created By')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('region')
                ->searchable(),
                Tables\Columns\TextColumn::make('socials')
                ->url(fn ($record) => $record->socials, shouldOpenInNewTab: true)
                    ->sortable(),
                
                Tables\Columns\ImageColumn::make('photos.photo_url')
                ->stacked()
                ->limit(3)
                ->limitedRemainingText(isSeparate: true),
                
                Tables\Columns\TextColumn::make('website')
                ->url(fn ($record) => $record->socials, shouldOpenInNewTab: true)
                    ->sortable(),
                        
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListVenues::route('/'),
            'create' => Pages\CreateVenue::route('/create'),
            'view' => Pages\ViewVenue::route('/{record}'),
            'edit' => Pages\EditVenue::route('/{record}/edit'),
        ];
    }
}

CreateVenue.php:

    <?php

namespace App\Filament\Resources\VenueResource\Pages;

use App\Filament\Resources\VenueResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use App\Models\VenuePhoto;

class CreateVenue extends CreateRecord
{
    protected static string $resource = VenueResource::class;

    protected function afterSave(): void
    {
        // Obtener el array de fotos subidas
        $uploadedPhotos = $this->data['photos'];
        dd($this->data['photos']);
        // Guardar las URLs en la tabla venue_photos
        foreach ($uploadedPhotos as $photo) {
            VenuePhoto::create([
                'venue_id' => $this->record->id, // ID del venue actual
                'photo_url' => $photo, // URL de la imagen
            ]);
        }
    }
}

Editvenue.php:

<?php

namespace App\Filament\Resources\VenueResource\Pages;

use App\Filament\Resources\VenueResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Models\VenuePhoto;

class EditVenue extends EditRecord
{
    protected static string $resource = VenueResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make(),
        ];
    }

    protected function afterSave(): void
    {
        // Obtener el array de fotos subidas
        $uploadedPhotos = $this->data['photos'];
        
        // Guardar las URLs en la tabla venue_photos
        foreach ($uploadedPhotos as $photo) {
            VenuePhoto::create([
                'venue_id' => $this->record->id, // ID del venue actual
                'photo_url' => $photo, // URL de la imagen
            ]);
        }
    }
}

Venue.php (model)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Venue extends Model
{
    use SoftDeletes;
    use HasFactory;

    protected $table = 'venues';

    protected $fillable = [
        'name',
        'address',
        'zip',
        'city',
        'state',
        'country',
        'lt',
        'lg',
        'description',
        'created_by',
        'socials',
        'website',
        'region'
    ];

    public function photos()
    {
        return $this->hasMany(VenuePhoto::class, 'venue_id');
    }

    public function events()
    {
        return $this->hasMany(Event::class, 'venue_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }
    
    protected $casts = [
        'photos' => 'array',
    ];

}
3
  • ¿El debug dd($this->data['photos']); que tienes en CreateVenue.php qué muestra?
    – A. Cedano
    Commented el 30 sept. a las 20:59
  • Hola @A.Cedano, no aparece en pantalla el dd, simplemente no ingresa alli
    – ClaudioZ
    Commented el 1 oct. a las 2:02
  • Pues si las inserciones se hacen, según dices, y el código no pasa por ahí, significa que está usando otro código para insertar.
    – A. Cedano
    Commented el 1 oct. a las 13:16

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.