Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to upload an image in Laravel 5.4

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?

like image 682
anonym Avatar asked Mar 11 '17 14:03

anonym


2 Answers

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">
like image 111
Marcin Nabiałek Avatar answered Oct 23 '22 07:10

Marcin Nabiałek


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">
like image 21
Ayman Elshehawy Avatar answered Oct 23 '22 07:10

Ayman Elshehawy