Unable to upload an image in Laravel 5.4
Asked Answered
F

3

7

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?

Fume answered 11/3, 2017 at 14:10 Comment(0)
S
27

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">
Saransk answered 11/3, 2017 at 14:17 Comment(1)
What a lapse. Thanks a lot.Fume
A
1

If you use Laravelcollective

                          {!! Form::open(['method'=>'post','files' => true,'url'=>'/hq/foods']) !!}

OR Using HTML

<form action="/hq/foods" method="POST" enctype="multipart/form-data">
Alroi answered 30/8, 2017 at 10:24 Comment(0)
P
1

you need to add enctype="multipart/form-data" in your from

Peptonize answered 23/12, 2019 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.