无法在 Laravel 5.4 中上传图片

Unable to upload an image in Laravel 5.4

使用 Laravel 5.4,我试图设置一个表单,用户可以在其中输入食物名称及其图像。在尝试上传 PNG 或 JPG 图片时,我得到以下 Validation Error:

The image must be an image.

如果我删除图像验证,我会得到 FatalErrorException:

Call to a member function getClientOriginalExtension() on null

这是Intervention/Image库提供的辅助函数。这可能意味着图片根本没有上传。

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();
}

我错过了什么?

上传图片需要添加:

enctype="multipart/form-data"

到您的表格,而不是:

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

你应该使用

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

如果你使用 Laravelcollective

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

或 使用 HTML

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

您需要在您的 from

中添加 enctype="multipart/form-data"