In the latest version of Media Library Pro, we have made its validation mechanisms even more powerful. Media Library Pro already comes with ValidatesMedia,
which helps you write validation rules with a fluent pattern.
If you are not familiar with the trait, this is how you could already use it in your request objects:
class PostRequest extends FormRequest
{
use ValidatesMedia;
public function rules()
{
return [
'images' => $this
->validateMultipleMedia()
->minItems(1)
->maxItems(5)
->extension('png')
->maxItemSizeInKb(1024)
->attribute('name', 'required')
];
}
}
This is a really clean way of validating your media, but because of how it worked under the hood, it did not work outside of a Request object. Good news: we have rewritten this trait, so you can now use it outside Request objects, too!
With this change, you can now start using the ValidatesMedia
trait inside Livewire components or even directly in a controller.
How it works with Laravel
In our example, we have a simple PostComponent that has a title field and an images field:
<form method="POST" wire:submit.prevent="submit">
<input type="text" wire:model="title">
<livewire:media-library
collection="images"
:model="$post"
wire:model="images"
rules="mimes:jpeg"
/>
<button type="submit">Save</button>
</form>
use Spatie\MediaLibraryPro\Livewire\Concerns\WithMedia;
class PostComponent extends Component
{
use WithMedia;
public $title = '';
public $images = [];
public Post $post;
public function submit()
{
$this->validate([
'title' => 'required'
]);
$this->post
->addFromMediaLibraryRequest($this->images)
->toMediaCollection('images');
}
...
}
Right now, only the title field is validated, but if we want to validate the images that are being added to the post, we simply have to do two things:
- Add the
ValidatesMedia
trait at the top of your Livewire class.
- Modify the
submit
method and add some validation rules.
use Spatie\MediaLibraryPro\Livewire\Concerns\WithMedia;
use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia;
class PostComponent extends Component
{
use WithMedia, ValidatesMedia;
...
public function submit()
{
$this->validate([
'title' => 'required',
'images' => [
$this->validateMultipleMedia()
->minItems(1)
->maxItems(4)
->extension('png')
]
]);
$this->post
->addFromMediaLibraryRequest($this->images)
->toMediaCollection('images');
}
...
}
This latest update provides more flexibility for validating media uploads directly in Livewire or controllers, streamlining the process. Allowing you to develop your apps even quicker!