Charrua's avatar

Testing image upload and validation failure

Hello, I’m trying to test file uploads inside a controller and validate it.

The problem is that validation is failing for image type and seems that the only data is getting onto the controller is the image name...

From the docs I can see

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function testAvatarUpload()
    {
        Storage::fake('courses');

        $file = UploadedFile::fake()->image('avatar.jpg');

        $response = $this->json('POST', '/courses', [
            'image' => $file,
        ]);

        // Assert the file was stored...
        Storage::disk('courses')->assertExists($file->hashName());
    }
}

Controller

public function store(Request $request)
{
        $request->validate([
            'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
   
        $image_path = $request->file('image')->store('courses');

        $course = new Course;
        $course->image_path = $image_path;
              
        return view('courses.show', compact('course'));
}

Any ideas on what I’m doing wrong? It seems that the image object is not reaching the controller. Thank you.

0 likes
2 replies
tykus's avatar
$response = $this->json('POST', '/courses', [
'image' => $file,
]);

You cannot upload a file using application/json

Please or to participate in this conversation.