如何在Laravel REST API中使用PUT方法更新图像? [英] How to update image with PUT method in Laravel REST API?

查看:58
本文介绍了如何在Laravel REST API中使用PUT方法更新图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Laravel构建REST API,以便用户需要更新其图像.但是,如果我在邮递员中使用PUT方法,它不会更新图像或将图像存储在指定的文件夹中.如果我改用POST,它会更新图像并保存在文件夹中.但是,由于我自定义要存储在DB中的名称,因此它不会将文件保存在数据库中.可能是什么原因.帮助真的很有必要.TIA.

I am trying to build a REST API with Laravel where users need to update their image. But, If I use PUT method in postman it does not update the image or store the image in designated folder. If I use POST instead it does update the image and also saves in the folder. But it does not save the file in database as I customize the name to store in DB. What could be the reason. Help is really necessary. TIA.

更新代码

public function update(Request $request, $id)
{
    $found = Partner::find($id);
    if (!$found) {
        return Response::json(['message' => 'Id not found'], 404);
    }
    $validatedData = Validator::make($request->all(), [
        'company_logo' => 'sometimes|mimes:jpg,png,jpeg|max:3048',
        'company_name' => 'sometimes|max:130',
        'company_email' => 'sometimes|email',
        'password'  =>  'sometimes|min:6',
        'phone'  =>  'sometimes|min:6|max:11',
        'address'  =>  'sometimes',
        'city'  =>  'sometimes|string',
        'country' =>  'sometimes|string' ,
        'business_category'  =>  'sometimes|string',
        'website_link' =>  'nullable|string',
        'facebook_page' =>  'nullable|string'
    ]);
    if ($validatedData->fails()) {
        return Response::json(['success' => false, 'message' => $validatedData->errors()], 400);
    }

    if ($request->hasFile('company_logo')) {
        $logo = $request->company_logo;
        $fileName = date('Y') . $logo->getClientOriginalName();
        $request->company_logo->storeAs('company_logo', $fileName, 'public');
        $found['company_logo'] = $fileName;
    }
    
    $found->update($request->all());

    return Response::json(['success' => true, 'message' => 'Partner updated successfully!', 
                           'updated_data' => $found], 200);
}

我的路线

Route::group(['prefix' => 'partner'], function () {
Route::post('store', [APIMemberController::class, 'store']);
Route::post('update/{id}', [APIPartnerController::class, 'update']); // This works
// Route::put('update/{id}', [APIPartnerController::class, 'update']); // This don't why?
});

存储伙伴

public function store(Request $request)
{
    $validatedData = Validator::make($request->all(), [
        'company_logo' => 'required|mimes:jpg,png,jpeg|max:3048',
        'company_name' => 'required|max:130',
        'company_email' => 'required|email|unique:partners',
        'password'  =>  'required|min:6',
        'phone'  =>  'required|min:6|max:11',
        'address'  =>  'required',
        'city'  =>  'required|string',
        'country' =>  'required|string' ,
        'business_category'  =>  'required|string',
        'website_link' =>  'nullable|string',
        'facebook_page' =>  'nullable|string'
    ]);

    if ($validatedData->fails()) {
        return Response::json(['success' => false, 'message' => $validatedData->errors()], 400);
    }

    // $saved = Partner::create($request->all());

    if ($request->hasFile('company_logo')) {
        $logo = $request->file('company_logo');
        $fileName = date('Y') . $logo->getClientOriginalName();
        $request->company_logo->storeAs('company_logo', $fileName, 'public');
    }

    $partner = new Partner();
    
    $partner->company_logo = $request->company_logo->getClientOriginalName();
    $partner->company_name = $request->company_name;
    $partner->company_email = $request->company_email;
    $partner->password = $request->password;
    $partner->phone = $request->phone;
    $partner->address = $request->address;
    $partner->city = $request->city;
    $partner->country = $request->country;
    $partner->business_category = $request->business_category;
    $partner->website_link = $request->website_link;
    $partner->facebook_page = $request->facebook_page;
    $partner->save();
    return Response::json(['success' => 'Partner created successfully!', 'created_partner' => $partner], 201);


}

推荐答案

我可以看到两个更改,这些更改应该可以通过更新功能为您提供所需的结果

I can see two changes which should get you the desired result with the update function

public function update(Request $request, $id)
{
    $found = Partner::find($id);
    if (!$found) {
        return Response::json(['message' => 'Id not found'], 404);
    }
    $validatedData = Validator::make($request->all(), [
        'company_logo' => 'sometimes|mimes:jpg,png,jpeg|max:3048',
        'company_name' => 'sometimes|max:130',
        'company_email' => 'sometimes|email',
        'password'  =>  'sometimes|min:6',
        'phone'  =>  'sometimes|min:6|max:11',
        'address'  =>  'sometimes',
        'city'  =>  'sometimes|string',
        'country' =>  'sometimes|string' ,
        'business_category'  =>  'sometimes|string',
        'website_link' =>  'nullable|string',
        'facebook_page' =>  'nullable|string'
    ]);
    if ($validatedData->fails()) {
        return Response::json(['success' => false, 'message' => $validatedData->errors()], 400);
    }

    if ($request->hasFile('company_logo')) {
        $logo = $request->company_logo;
        $fileName = date('Y') . $logo->getClientOriginalName();

    //Get the path to the folder where the image is stored 
    //and then save the path in database
        $path = $request->company_logo->storeAs('company_logo', $fileName, 'public');
        $found['company_logo'] = $path;
    }
    
    //update with all fields from $request except 'company_logo'

    $found->update($request->except('company_logo'));

    return Response::json(['success' => true, 'message' => 'Partner updated successfully!', 
                           'updated_data' => $found], 200);
}

只需将其包含在此处的答案中即可:

Just to include it in the answer here:

如果有人想使用PUT或PATCH请求来包含文件上传的表单,则

If someone wants to use a PUT or PATCH request for form containing file uploads

<form action="/foo/bar" method="POST">
    @method('PUT')

    ...
</form>

通过任何JavaScript框架,例如 vue

via any javascript framework like vue

let data = new FormData;
data.append("_method", "PUT")

axios.post("some/url", data)

我已经做到了.但是我的问题是为什么在更新方法中,PUT对Laravel不起作用?

I have done that. But my question is now why PUT does not work for Laravel in update method?

这不是因为Laravel,而是PHP的局限.在 PUT 请求期间,PHP不会像在 POST 请求期间那样填充超级全局 $ _ FILES .

It's not because of Laravel, it's a PHP thing/limitation. PHP doesn't populate the super global $_FILES during a PUT request as it does during a POST request.

要通过PHP中的 Put/方法访问文件上传,请参见

To access a file upload via Put/ method in PHP see features.file-upload.put-method

因此,发出 POST 请求以进行文件上载并使用方法欺骗以使Laravel知道该请求针对的是与 PUT 方法相对应的路由,可能会更容易

Hence it's probably easier to make a POST request for file-uploads and use method spoofing to let Laravel know that the request is for a route corresponding to PUT method

这篇关于如何在Laravel REST API中使用PUT方法更新图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆