PHP code example of codebyray / livewire-media-uploader
1. Go to this page and download the library: Download codebyray/livewire-media-uploader library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
codebyray / livewire-media-uploader example snippets
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
public function update(User $user, Post $post): bool
{
return (string) $post->user_id === (string) $user->getKey();
}
}
use Spatie\Image\Enums\Fit;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class Post extends Model implements HasMedia
{
use InteractsWithMedia;
public function registerMediaCollections(): void
{
// Multi-file collection.
$this->addMediaCollection('photos')
->useDisk('public')
->withResponsiveImages();
// Single-file collection. Each new upload replaces the existing file.
$this->addMediaCollection('avatars')
->singleFile();
}
public function registerMediaConversions(?Media $media = null): void
{
$this->addMediaConversion('thumb')
->fit(Fit::Contain, 256, 256)
->performOnCollections('photos', 'avatars')
->nonQueued();
}
}
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Livewire\Component;
class PostCreate extends Component
{
public string $title = '';
public string $body = '';
public ?int $pendingPostId = null;
protected function rules(): array
{
return ['title' => ' // Fire once per collection rendered on the page
$this->dispatch('media:attach', model: 'post', id: $post->id, collection: 'images', channel: 'post-images');
}
#[On('media-attached')]
public function afterMediaAttached(string $model, string|int $id): void
{
if ($this->pendingPostId && (int)$id === (int)$this->pendingPostId) {
$this->pendingPostId = null;
$this->redirectRoute('posts.show', ['post' => $id], navigate: true);
}
}
public function render() { return view('livewire.posts.post-create'); }
}
html
resources/views/vendor/media-uploader/themes/tailwind/media-uploader.blade.php
resources/views/vendor/media-uploader/themes/bootstrap/media-uploader.blade.php
bash
php artisan config:clear
html
<livewire:media-uploader
:for="$user"
collection="avatar"
:multiple="false"
:showList="false"
preset="images"
/>
html
<livewire:media-uploader :for="$user" collection="images" preset="images" :skipExactDuplicates="true" />
html
<livewire:media-uploader
:for="$post"
collection="images"
preset="images"
:watermark="true"
/>