Laravel: Validate an Uploaded File is an Image

One thing I’ve seen asked often in the Laravel forums is how to validate that an uploaded file is an image. The quick couple of snippets below detail how to perform this common task.

~

One thing I’ve seen asked often in the Laravel forums is how to validate that an uploaded file is an image. The quick couple of snippets below detail how to perform this common task.

Create a view called form.blade.php and place the following contents:

<!doctype html>
<html lang="en">
<head>
    <title>File Upload</title>
</head>
<body>
@if (Session::has("message"))
    
@endif
<hr />



</body>
</html>

The code below should be placed in a controller, or quickness I’ve just dropped it into a route.

You can use the following logic with the Laravel validator to check the file is an image:

Route::get('/', function()
{
    // Return our basic form view
    return View::make("form");
});

Route::post('/', function()
{
    // Build the input for our validation
    $input = array('image' => Input::file('image'));

    // Within the ruleset, make sure we let the validator know that this
    // file should be an image
    $rules = array(
        'image' => 'image'
    );

    // Now pass the input and rules into the validator
    $validator = Validator::make($input, $rules);

    // Check to see if validation fails or passes
    if ($validator->fails())
    {
        // Redirect with a helpful message to inform the user that 
        // the provided file was not an adequate type
        return Redirect::to('/')->with('message', 'Error: The provided file was not an image');
    } else
    {
        // Actually go and store the file now, then inform 
        // the user we successfully uploaded the file they chose
        return Redirect::to('/')->with('message', 'Success: File upload was successful');
    }
});