How to update image with PUT method in Laravel REST API?

耗尽温柔 提交于 2021-01-29 08:31:09

问题


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.

Update Code

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

My route

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

Storing partner

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


}

回答1:


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:

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

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

    ...
</form>

via any javascript framework like vue

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

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


来源:https://stackoverflow.com/questions/64887893/how-to-update-image-with-put-method-in-laravel-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!