Media Library Pro: Vue, React and Blade components to handle uploads (sponsor)


November 16th, 2020


I’m proud to announce that Media Library Pro is now available. Media Library Pro is an add-on package for our free Media Library base package. It contains a set of Blade, Vue and React components that make it easy to upload files to media library and to manage files inside of a media library collection.

In this blog post, I’d like to introduce Media Library Pro to you.

Getting to know Laravel Media Library

Before getting into the Pro components, let’s first get you up to speed with what the free version of Media Library can do for you. If you’re already familiar with the free version of Media Library, you can skip this section.

Shortly said, Media Library can associate files with Eloquent models. You can, for instance, associate images with a blog post model.

2 ->addMedia($pathToFile)
3 ->toMediaCollection('images');

In your Blade view, you can retrieve URLs to the associated images.

1@foreach($blogPost->getMedia('images') as $mediaItem)
2 <img src="{{ $mediaItem->getUrl() }}" alt="my image" />

Media Library can also generate all sorts of conversions. Using the blog post example, you probably don’t want to display the original image in a list of blog posts. It’s more likely that you want to show a smaller version of the image, a thumbnail, on such a list.

You can let Media Library generate converted images by defining a conversion on the model. Here’s a conversion that could be put in the BlogPost model.

1// somehwere in the BlogPost model
3public function registerMediaConversions(Media $media = null): void
5 $this->addMediaConversion('thumb')
6 ->width(300)
7 ->height(300)
8 ->sharpen(10);

With that in place, Media Library will generate a thumbnail that fits in a 300×300 square. The image is also sharpened a bit, so it looks crispy. Of course, that thumbnail will be much smaller than the original image. You can get to the URL of a conversion simply by using the conversion’s name as an argument to getUrl.

1@foreach($blogPost->getMedia('images') as $mediaItem)
2 <img src="{{ $mediaItem->getUrl('thumb') }}" alt="my thumbnail" />

In the example above, we’ve defined a single thumb conversion, but you can add as many conversion to a model as you like.

The Media Library can do a whole lot more. It can handle multiple collections, work with multiple filesytems, create zips on the fly to download multiple files, use a customized directory structure, save bandwidth using responsive images and much more.

In these two videos, I show you the basics of Laravel Media Library.

Want to see more videos like this? Check out our free video course on how to use Laravel Media Library.

The problem with traditional uploads

Before exploring Media Library Pro, let’s first explained why we built it in the first place. Here’s how a traditional upload form might look like. It uses a regular input of type file.

Here’s the Blade view that renders that form. It was taken from this demo application

1<form method="POST" enctype="multipart/form-data">
2 <x-grid>
3 @csrf
5 <x-field label="name">
6 <x-input id="name" name="name" placeholder="Your first name" />
7 </x-field>
9 <x-field label="file">
10 <input type="file" name="file">
11 @error('file')
12 {{ $message }}
13 @enderror
14 </x-field>
16 <x-button dusk="submit">Submit</x-button>
17 </x-grid>

There are two big problems with this standard upload element.

First, the upload process only starts when the form is submitted. For small files in small forms, this might not be a problem. But imagine you’re uploading a multi MB file in a form. When submitting the form, you now have to wait for the upload to complete before seeing the submission results.

The second problem is something that has bothered me for a long, long time. Imagine that the input field is part of a form of which some fields are required. You’re selecting a file, submitting the form, leaving some of the required fields empty. You get redirected back to the form where error messages are now displayed. Your previous file selection is gone, and you need to select the file again. Over the years, I’ve said many curse words when this happened to me.

I’m also pretty sure that, as a developer, you probably lost time debugging uploads because you forgot to add enctype="multipart/form-data" to the form.

In this video, you’ll see a demo of all these problems.

Let’s look at how all of these problems are solved in Media Library Pro.

Introducing Media Library Pro

Media Library Pro is a paid add-on package that offers Blade, Vue, and React components to upload files to your application. It ships with two components. The first one is the attachment component. It is meant to be used on a public-facing page where you want users to upload one or multiple files.

The second one is called the collection component. This one can manage the files in an existing collection. It is meant to be used in the admin part of your app.

Both of these components are available as Vue, React and Blade components. Under the hood, the Blade components are powered by Caleb’s excellent Livewire package.

These components are straightforward to install and are documented in great detail.

Let’s take a look at both the Attachment and Collection component. In the remainder of the blog post, I’ll use the Blade version of the examples, but rest assured that everything shown can also be done with the Vue and React counterparts.

The Attachment component

If you want to see a quick demo of the attachment component, check out this video.

You can find the code used in that video in this repo on GitHub. All further code examples are taken from that app.

To get started with the Attachment Blade component you’ll have to use x-media-library-attachment in your view.

1<form method="POST">
2 @csrf
4 <input id="name" name="name">
6 <x-media-library-attachment name="avatar"/>
8 <button type="submit">Submit</button>

Here’s how it looks like after we’ve selected a file but before submitting the form.

The x-media-library-attachment has taken care of the upload. The file is now stored as a temporary upload. In case there are validation errors when
submitting the form, the x-media-library-attachment will display the temporary upload when you get redirected back to
the form. There’s no need for the user to upload the file again.

Here’s the form request used to validate the uploaded.

1namespace App\Http\Requests\Blade;
3use Illuminate\Foundation\Http\FormRequest;
4use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia;
6class StoreBladeAttachmentRequest extends FormRequest
8 use ValidatesMedia;
10 public function rules()
11 {
12 return [
13 'name' => 'required',
14 'media' => ['required', $this->validateSingleMedia()
15 ->maxItemSizeInKb(3000),
16 ],
17 ];
18 }

By applying the ValidatesMedia trait, you get access to the validateSingleMedia, which allows you to validate the upload. You can chain on many validation methods, which are documented here.

In your controller, you can associate the upload file to any model you’d like.

2 ->addFromMediaLibraryRequest($request->media)
3 ->toMediaCollection('images');

And that is all you need to do!

The attachment component can be used to handle multiple uploads as well. In this video, you’ll see how that is done.

The Collection component

You can manage the entire contents of a media library collection with x-media-library-collection component. This
component is intended to use in admin sections.

Here is an example where we will administer an images collection of a $formSubmission model.

1<form method="POST">
2 @csrf
3 <x-field label="name">
4 <x-input id="name" name="name" autocomplete="off" placeholder="Your name"
5 value="{{ old('name', $formSubmission->name) }}"/>
6 </x-field>
8 <x-field label="Images">
9 <x-media-library-collection
10 name="images"
11 :model="$formSubmission"
12 collection="images"
13 max-items="3"
14 rules="mimes:png,jpeg"
15 />
16 </x-field>
18 <x-button dusk="submit" type="submit">Submit</x-button>

Here’s how that component looks like:

This component will display the contents of the entire collection. Files can be added, removed, updated, and reordered.

In this video, you’ll see the collection component in action.

To validate the response of the form, a form request like this one can be used:

1namespace App\Http\Requests\Blade;
3use Illuminate\Foundation\Http\FormRequest;
4use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia;
6class StoreBladeCollectionRequest extends FormRequest
8 use ValidatesMedia;
10 public function rules()
11 {
12 return [
13 'name' => 'required',
14 'images' => [$this->validateMultipleMedia()
15 ->maxItems(3)
16 ->itemName('required'),
17 ],
18 ];
19 }

Again, you need to ValidatesMedia trait. This time the validateMultipleMedia should be used. You can chain on the other validation methods, which are documented here.

In the controller, you can associate the media in the collection component with your model using the syncFromMediaLibraryRequest method.

Here’s the relevant code in the controller of the demo app.

2 ->syncFromMediaLibraryRequest($request->images)
3 ->toMediaCollection('images');

Adding custom properties

When using the collection component, you probably want to add some extra fields to be displayed. We’ve made this a straightforward thing to do.

In the screenshot below, we added the Extra field field.

You can achieve this by passing a blade view to the fields-view prop of the x-media-library-collection.

2 name="images"
3 :model="$formSubmission"
4 collection="images"
5 max-items="3"
6 rules="mimes:png,jpeg"
7 fields-view="uploads.blade.partials.custom-properties"

In that custom-properties view, you can put anything that should be displayed in the right half of the collection component.

Here’s the content of that custom-propertiesview.

3<div class="media-library-field">
4 <label class="media-library-label">Extra field</label>
5 <input
6 dusk="media-library-extra-field"
7 class="media-library-input"
8 type="text"
9 {{ $mediaItem->customPropertyAttributes('extra_field') }}
10 />
12 @error($mediaItem->customPropertyErrorName('extra_field'))
13 <span class="media-library-text-error">
14 {{ $message }}
15 </span>
16 @enderror

In the form request, you can use the customProperty to validate any extra custom attributes. The second argument of the function can take any validator in Laravel.

1namespace App\Http\Requests\Blade;
3use Illuminate\Foundation\Http\FormRequest;
4use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia;
6class StoreBladeCollectionCustomPropertyRequest extends FormRequest
8 use ValidatesMedia;
10 public function rules()
11 {
12 return [
13 'name' => 'required',
14 'images' => [$this->validateMultipleMedia()
15 ->maxItems(3)
16 ->itemName('required|max:30')
17 ->customProperty('extra_field', 'required|max:30'),
18 ],
19 ];
20 }

In the controller where you process the form submission, you should use the withCustomProperties method to whitelist any extra attributes that you want to sync with your media.

2 ->syncFromMediaLibraryRequest($request->images)
3 ->withCustomProperties('extra_field')
4 ->toMediaCollection('images');

Here’s a video where you see all of this in action.

Customizing the look and feel

By default, both the Attachment and Collection components already look good. Probably you’d like to adapt them so they match the look of your app.

Luckily, this is easy to do. The styles that ship with Media Library Pro can be used by importing or linking dist/styles.css. The styles were built with a default tailwind.config.js.

You can customize the styles by importing src/styles.css and run every @apply rule through your own tailwind.config.js

1/* app.css */
3@tailwind base;
5@tailwind components;
7@tailwind utilities;
9@import "src/styles.css";

To view this in action, watch this video.

How temporary files are used

To achieve that behavior where uploaded files are preserved when a form validation error occurs, we use temporary uploads. In this video, I explain how that works.

Testing the components

Inside the private spatie/laravel-medialibrary-pro repo, there are a lot of tests to make sure the back end integration and the Vue, React, and Blade front end components are working as expected.

We also wanted to have browser tests that ensure that front end components work perfectly with the back end and vice versa. That’s why we added Dusk tests in our demo application. You can see them here.

Let’s take a look at one of them:

2 * @test
3 *
4 * @dataProvider routeNames
5 */
6public function it_can_handle_a_single_upload(string $routeName)
8 $this->browse(function (Browser $browser) use ($routeName) {
9 $browser
10 ->visit(route($routeName))
11 ->type('name', 'My name')
12 ->attach('@main-uploader', $this->getStubPath('space.png'))
13 ->waitForText('Remove')
14 ->waitUntilMissing('')
15 ->press('@submit')
16 ->assertSee('Your form has been submitted');
18 $this->assertCount(1, FormSubmission::get());
20 $this->assertEquals('space.png', FormSubmission::first()->getFirstMedia('images')->file_name);
21 });

This test will upload a file and make sure that the file is associated with a model after the form is submitted.

A thing to note here is that @dataProvider attribute. This will make PHPUnit run the test for each result returned by the routeNames function defined in the same file.

1public function routeNames(): array
3 return [
4 ['vue.attachment'],
5 ['react.attachment'],
6 ['blade.attachment'],
7 ];

You can see that in combination with the routeNames function, the it_can_handle_a_single_upload will run for the vue.attachment, react.attachment and blade.attachment routes. Visiting these routes will display the form that will use the Vue, React, or Blade component, respectively. So, this one test covers a lot of logic. It makes sure that the component work using any technology. This gives us a lot of confidence that all of the components are working correctly.

Another cool thing to note is that the Dusk tests also run on GitHub Actions. Here’s the workflow contained in the repo.

In closing

In my mind, these front end components were a final missing part in the media library experience. I’m delighted how they turned out and how easy it now becomes to upload and manage media in a Laravel app.

Because we invested quite some time in getting these components just right, we decided to make spatie/laravel-media-library-pro a paid package. You can buy a license on our website. As mentioned previously, the package contains Blade, Vue, and React components. You’ll find the extensive documentation [here].

After you’ve bought a license, you’ll immediately get access to the private spatie/laravel-medialibrary-pro repo. Even if you’re not in the market for kick-ass upload components, it still might be worthwhile to buy them: the source code contains many interesting things you might learn from.

At the time of writing, we are running a launch promo. Use this coupon code when buying Media Library Pro to get a 20% discount:


Our whole team gave input on these components, so I consider it a team effort. My colleague Adriaan coded up most of the JavaScript. Willem, as always, made everything look gorgeous.

For those wondering, the base media library package is still free, and we’ll always keep it free.

Be sure also to check out our other paid products and our extensive collection of free open source packages.

Filed in:

Freek Van der Herten

PHP developer, Laravel enthousiast at, blogger, and package creator.