Courses

Testing in Laravel 11: Advanced Level

Testing File Uploads with Storage Fake

Summary of this lesson:
- Use Storage::fake() for file upload testing
- Simulate file uploads in tests
- Assert file existence and storage
- Check file names and storage locations
- Verify upload functionality

Let's talk about testing the file uploads and checking various things:

  • Whether the file upload was successful
  • Whether the file is where it belongs
  • Whether the file name is assigned successfully.

Like a few other "external" things in Laravel, file uploads need to be faked for testing.

So, you don't work with the actual file uploads to the real storage. You fake the Storage driver, then Laravel, with its testing mechanism, puts those files elsewhere in a separate temporary folder, and then you assert whether that Storage temporary fake disk contains the file.


Scenario Example

For example, you have a Controller to store a product, and one of the fields is photo. You store the photo in the products folder and save the filename as a string to the photo database field.

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
 
class ProductController extends Controller
{
// ...
 
public function store(Request $request): RedirectResponse
{
$product = Product::create($request->all());
 
if ($request->hasFile('photo')) {
$filename = $request->file('photo')->getClientOriginalName();
$request->file('photo')->storeAs('products', $filename);
$product->update(['photo' => $filename]);
}
 
return redirect()->route('products.index');
}
 
// ...
}

Test

The start of the test is...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord