Under the hood: How fake uploaded files work in Laravel

Share on facebook
Share on twitter
Share on linkedin


This is the first post of the new “Under the hood” series where I’ll try to explain how things work behind the scenes. I am going to pick topics from my day to day work from various areas like Laravel, JavaScript, Vue.js etc.

Testing file upload

It is quite common that a web application has file upload, so we want to cover this functionality with tests. Laravel offers a method to create a fake upload file using the following method: UploadedFile::fake()->image(‘avatar.jpg’); For more information about how to test file upload please check the Laravel documentation here.
Let’s see how the UploadedFile::fake() works. The fake method simply creates and returns a new instance of the Testing\FileFactory class:

The FileFactory

The FileFactory has two public methods, we can create a generic file with a given name and file size, or we can create an image with specific width and height.


This method creates a temporary file with the php’s built in tmpfile() function. This resource is used to instantiate a new Testing\File, set the name of the file and the desired file size.

This newly created File is going to be used when you make a post request from the test case, like this:


The basic principle of the image method is similar to the create, but it actually creates a black image with the given dimensions:

The image is being generated in the generateImage method. As of the time of writing the image generation support png and jpeg images. It also creates a temporary file, generates the image according to the $type argument and writes the content to the temporary file.

Using the fake uploaded file makes it is easy to test the file and image uploads. I hope this article was useful to understand how it works.

Related articles

If you like this article, please check the other posts of the series here.

0 0 vote
Article Rating

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook

And the winners are …

As already announced we are going to launch 42workflows in the near future – a free open source package that will help you automate your

symphony process

Symfony Process with Laravel

Are you using ‘exec’, ‘passthru’, ‘shell_exec’ and ‘system’ php functions in your Laravel project? Taking care of security risks by yourself, as well as expecting

Notify of
Inline Feedbacks
View all comments