The check and response

Validating an image is a bit more complex than our previous rules, so let’s begin by detailing the steps involved:

Verify the supplied string begins with "data:image/{{mime}};base64," Strip the prefix and write the remaining data to a temporary file. Create an instance of the Illuminate\Http\UploadedFile class and populate its parameters to point to the temporary file. Use Laravel’s native image validation rule to verify the file is genuine. Remove the temporary file.

In order for the rule to work, we need only supply a single parameter — the expected / required mime type of the file. Now that we know what should be happening, let’s take a look at the logic of the passes method:

public function passes($attribute, $value)

{

if (! Str::startsWith($value, "data:image/{$this-

>parameters[0]};base64,")) {

return false;

} $result = validator(

['file' => $this->createTemporaryFile($value)],

['file' => 'image']

)->passes(); fclose($this->file); return $result;

}

You’ll notice that we have a createTemporaryFile method, which handles the writing of the file to disk. Let’s take a look at the logic of this method:

protected function createTemporaryFile($data)

{

$this->file = tmpfile(); fwrite($this->file, base64_decode(Str::after($data, 'base64,'))); return new UploadedFile(

stream_get_meta_data($this->file)['uri'], 'image',

'text/plain', null, null, true

);

}

One important thing to remember is that we have to call fclose AFTER we run the validation, otherwise the file will be automatically deleted and the validation will fail since the image does not exist.

Next, we’ll need to write an error message to respond with when the user has supplied an invalid image or an image with an incorrect MIME: