Unable to upload an image in Laravel 5.4

anonym picture anonym · Mar 11, 2017 · Viewed 8.4k times · Source

Using Laravel 5.4, I'm tring to setup a form where a user can enter a food name and its image. While trying to upload a PNG or JPG image, I get the following Validation Error:

The image must be an image.

If I remove the validation for image, I get a FatalErrorException:

Call to a member function getClientOriginalExtension() on null

which is a helper function provided by Intervention/Image library. This could mean that the image didn't upload at all.

FORM

<form action="/hq/foods" method="POST">
    {{ csrf_field()  }}

    <input type="text" name="name">
    <input type="file" name="image">
    <button type="submit" class="btn btn-success ">
        ADD FOOD ITEM
    </button>
</form>

CONTROLLER

public function store(Request $request) {

    $this->validate($request, [
        'name'              => 'required|min:2|max:255',
        'image'             => 'required|image'
    ]);

    $food_category = FoodCategory::find($request->food_category_id);
    $food = new Food;
    $food->name = $request->name;

    $image = $request->file('image');
    $filename = time() . '.' . $image->getClientOriginalExtension();
    $location = public_path('img/foods/' . $filename);
    Image::make($image)->resize(800, 400)->save($location);
    $food->image = $filename;

    $food->save();

    Session::flash('success',
        '
        <h4>Success!</h4>
        <p>The food item has been added to the Menu.</p>
    ');
    return back();
}

What am I missing?

Answer

Marcin Nabiałek picture Marcin Nabiałek · Mar 11, 2017

To upload images you need to add:

enctype="multipart/form-data"

to your form so instead of:

<form action="/hq/foods" method="POST">

you should use

<form action="/hq/foods" method="POST" enctype="multipart/form-data">