Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Testing dynamic file uploads with Laravel

David Carr

Laravel Framework Tutorials

When working with file uploads where the file name is generated, how do you know what the file name is and then test it exists in a test.

First in a controller doing a file upload with a store call which will store the file into a files folder in the public disk, if you don't need to specify the desk the leave off the second param.

$path = $request->file('name')->store(

//when no disk is required

$path = $request->file('name')->store('files');

Now this method would return the $path as its return.

Then In a test use the storage fake which tells Laravel to fake a file upload


To fake an upload you can use:


 To assert the file exists you can check the file in storage:


But if the file is stored dynamically you won't know the file name in which case you will need to look inside the response from the test. The response is not JSON but a test response. In order to covert this to json use decodeResponseJson on the response. Then you can use json as normal.

Putting it all together:

test('can upload file', function () {


    $response = post('api/v1/file', [
        'name' => UploadedFile::fake()->image('avatar.jpg'),

    $path = $response->decodeResponseJson()['data']['path'];




Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!


My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.