Laravel 在 null 上调用成员函数 isValid()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37501373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:53:13  来源:igfitidea点击:

Laravel Call to a member function isValid() on null

phplaravel

提问by Cruzito

In my project users can upload stuff and attach an image. I have a controller where I do a isValid check on the file input. Everything works great as long as you select a file. When I don't select a file I get this error

在我的项目中,用户可以上传内容并附加图像。我有一个控制器,我在其中对文件输入进行 isValid 检查。只要您选择一个文件,一切都会很好。当我不选择文件时,我收到此错误

Call to a member function isValid() on null

On this line of code:

在这行代码中:

if (Input::file('image')->isValid())

The error is obvious since I don't select an image but I actually have no idea how I can fix this.

错误很明显,因为我没有选择图像,但实际上我不知道如何解决这个问题。

If anyone can help I'd be very happy :) Thanks in advance!

如果有人可以帮助我会很高兴:) 提前致谢!

回答by Ekene Oguikpu

add enctype="multipart/form-data"to your form

添加enctype="multipart/form-data"到您的表单

回答by Pratik Soni

First you need to check if your request is containing that file / input or not.

首先,您需要检查您的请求是否包含该文件/输入。

Determining If A File Was Uploaded

确定文件是否已上传

if (Request::hasFile('image'))
{
    /*Determining If An Uploaded File Is Valid*/
    if (Request::file('image')->isValid())
    {
        //
    }
}

Just for your info also make sure you are getting file while posting. enctype="multipart/form-data"

仅供您参考,还请确保您在发布时获取文件。 enctype="multipart/form-data"

You can use any of Input and Request facade. Input class is also referencing to \Illuminate\Http\Requestin laravel

您可以使用任何输入和请求外观。输入类也在\Illuminate\Http\Requestlaravel 中引用