Search code examples
laravelfrontendlaravel-livewire

Multiple Forms / Child & Parent Forms in one page with Laravel Livewire


I have two forms one is uploading the images and saving them to the database, After saving its return Images ids. The second form is my main form and I want to use that image's id in the parent form as an input file.

Here is the main page HTML (Parent Form):-

<div class="container mt-5">
<div class="row">
    <h1 class="text-center my-2">Laravel Examples</h1>

    @livewire('multiple-image-upload', ['action' => 'add'])

    <form action="#" method="get">

        <input type="text" name="first_name" {{old('first_name')}}>
        <input type="text" name="last_name" {{old('last_name')}}>

        @if(!empty($uploadedImageIds))
            <input type="hidden"  value="{{$uploadedImageIds}}">
        @endif

        <input type="submit"  name="submit_add_category">

    </form>

</div>

and here is blade file of livewire-view which uploadeds the images

<form wire:submit.prevent="uploadFiles" enctype="multipart/form-data">

    <input type="file" wire:model="images" multiple accept="image/*" >

    <div wire:loading wire:target="images">Uploading the images...</div>

    @if( !empty( $images ) )

        <p>Preview your images before uploading</p>

        @foreach ( $images as $image )

            <img src="{{ $image->temporaryUrl() }}" alt="" style="width: 200px;" >

            @error('images.'.$loop->index)
                    <span style="color: red;" >{{ $message }}</span>
            @enderror

            <p>{{$image->getClientOriginalExtension()}}</p>
            <p>{{$image->getClientOriginalName()}}</p>
            <p>{{\App\Helpers\Helper::getFileSize($image->getSize())}}</p>
            <p wire:key="{{$loop->index}}" wire:click="removeImage({{$loop->index}})">Remove</p>

        @endforeach

        <button type="submit" >Upload Images</button>
    @endif

</form>

@if(!empty($uploadImages))
    <p>Preview your images after uploading</p>
    <input type="hidden" value="{{$uploadedImageIds}}">
    @foreach($uploadImages as $uploadImage)
        <img src="{{ $uploadImage['link'] }}" alt="" style="width: 500px;" >
        <p wire:click="deleteImage(11)">Remove</p>
    @endforeach
@endif

Any solution in which I can share the uploaded images in the main form?

Thanks in advance


Solution

  • use events, after any updated completion for the images property, emit an event to parent with the updated value you need. Eg

    // in the child
    public function updatedImages()
    {
      $this->emitUp('imagesIdEvent', ['imagesIds' => $images]);
    }
    
    // in parent
    protected $listeners = [
      'imagesIdEvent'
    ];
    
    public function imagesIdEvent($images)
    {
      dd($images);
    }