Search code examples
laravellaravel-livewire

Laravel Livewire refresh view before slow upload


I have a livewire component, that implements the Spatie Media Library Pro component:

// file-upload.blade.php
<form method="POST" wire:submit.prevent="submit">
  @csrf
  <div class="mb-3">
    <x-media-library-attachment name="media" :rules="$mimeTypes" key="mediaLibrary"/>
  </div>
  @if($uploading)
    <h2>Please wait...</h2>
  @endif
  <input type="submit" class="btn btn-primary btn-bg" />
</form>

I would like to show an uploading message, as the request is quite slow (@if($uploading) above).

The problem is, if I do something like this:

public function submit(){
  $this->validate([
    'media' => 'required|min:1',
  ]);
  
  $this->uploading = true;

  \Auth::user()->currentTeam
    ->addFromMediaLibraryRequest($this->media)
    ->toMediaCollection($this->collection);

  $this->clearMedia();

  return redirect()->route('media.index', ['collection' => $this->collection]);
}

The line $this->uploading = true; only refreshes my page when the whole function finishes — which is after the upload finishes.

Is there a way I can show this, then upload the file? Most other routes I have gone down either break the validation, I've tried using @entangle and toggling the $uploading from the front end but nothing seems to be working for me.

I think I have decided that I would like to keep to what I have, but either asynchronously start the upload, or refresh the view faster.


Solution

  • You can use the Livewire Loading States (https://www.laravel-livewire.com/docs/2.x/loading-states)

    <form method="POST" wire:submit.prevent="submit">
      @csrf
      <div class="mb-3">
        <x-media-library-attachment name="media" :rules="$mimeTypes" key="mediaLibrary"/>
      </div>
      <input type="submit" class="btn btn-primary btn-bg" />
    </form>
    <div wire:loading wire:target="submit">
       Loading...
    </div> 
    

    PD: I don't test it before in a form