【问题标题】:Call to a member function store() on null in Laravel 5.5 using postman使用邮递员在 Laravel 5.5 中调用 null 上的成员函数 store()
【发布时间】:2018-11-19 18:17:35
【问题描述】:

我正在使用 Postman 测试文件上传,但我总是收到此错误。我已经尝试在 Postman 请求的标题中添加和删除字段“multipart/form-data”,但没有结果。

Postman screenshot

我的代码:

public function update(Request $request, $id) {
    $validator = Validator::make($request->all(), [
        'name' => 'string|max:255',
        'second_name' => 'string|max:255',
        'description' => 'string|max:255',
        'gender' =>  'string|max:255',
        'admin' =>  'boolean',
        'birthday'  => 'string|max:255',
        'email' => 'string|email|max:255|unique:users',
        'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
        'file' => 'file',
    ]);

    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()], 401);
    }

    $user = User::find($id);
    $user->name = $request->input('name');
    $user->second_name = $request->input('second_name');
    $user->description = $request->input('description');
    $user->gender = $request->input('gender');
    $user->admin = $request->input('admin');
    $user->birthday = $request->input('birthday');
    $user->email = $request->input('email');
    $user->imageUrl = $request->file('file')->store('images');

    if($user->save()) {
        return new $user;
    }
}

【问题讨论】:

    标签: laravel laravel-5 storage postman


    【解决方案1】:

    您收到错误消息,因为您的请求中没有正确设置文件。

    由于$request->file('file')返回null,而你试图在null上调用方法,导致异常。

    当使用 Postman 向 Laravel 发出 PUT 或 PATCH 请求时,必须采用与平时略有不同的方法。

    由于 Laravel 处理 PUT 和 PATCH 请求的方式,您需要在 Postman 中将您的请求作为 POST 请求发送,并在标头中提供 _method 和值 PUT。这是 Laravel 所期望的。

    如果这是必填字段,我还建议将文件的验证规则更改为以下内容:

    'file' => 'file|required'

    这将使您的 API 故障排除更加容易。如果请求中未检测到文件,将提供 JSON 错误响应。

    【讨论】:

    • 谢谢,我想我是作为正文发送的?作为标头,我正在发送不记名令牌。是的,添加必填字段会告诉我“文件”是必需的,因此不会检测到该文件。
    • 对不起,我不知道我怎么看错了你的截图。我已经更新了我的答案。请尝试使用 Postman 中的 x-www-form-urlencoded 选项发送您的输入。如果您在向 Laravel API 发出 PUT 请求时未指定此选项,则不会在您的请求中检测到提供的值。
    • 与 form-data 选项不同,x-www-form-urlencoded 选项不能让我从我的计算机上传文件作为正文。
    • 我已经用另一个潜在的解决方案更新了我的答案
    • 非常感谢,我将请求从 put 更改为 post,现在可以使用了。
    猜你喜欢
    • 2017-04-08
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2018-09-06
    • 2020-10-28
    • 2020-09-08
    相关资源
    最近更新 更多