Feature Test File / Image Upload Validation in Laravel

Here is how you can test the image or file uploads in your PHPUnit feature test in Laravel.

Let’ say you have a Post Model in your application which also has an image parameter.

Here is how the PostFactory looks like

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Post;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
    $image = 
    return [
        'title' => $faker->sentence,
        'content' => $faker->paragraph,        
        'image' => $faker->image('public/storage/images',640,480, null, false),

Here is how the validation rules looks like

Livewire Component Library
$rules = [
            'title' => 'required',
            'content' => 'required',
            'image' => 'required|image|mimetypes:image/jpeg,image/png,image/jpg'

If you use the factory method in your phpunit test, The test will fail with error The given data was invalid., since we are only passing the image name and not the actual image for validaiton.

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

Here is how you can use \Illuminate\Http\UploadedFile::fake() in your tests.

/** @test */
public function admin_user_can_add_new_post(){
   // Given that we have a signed in user

   $tag = factory('App\Post')->make(['image' => UploadedFile::fake()->create('test.png', $kilobytes = 0)]);

   $this->post('/admin/tags', $tag->toArray());
   $this->assertDatabaseHas('tags', ['name' => $tag->name]);

That’s all about using UploadedFile to test file uploads in Laravel.

Site Footer