Search code examples
phplaravellumen

Laravel lumen doesn't update correctly


When i want to update a name with postman the name will be updated but not to the name that i want it to be updated.

For instance i want to update the name: Jan to Pieter. but when i place the name Pieter in postman it will update but it won't update to the name Pieter. The updated name is now Tijn.

Here is my code if that is helpfull

$router->put('dogs/{id}', function(Request $request, $id){
    $data=[];

    if ($request->has('name')){
        $data['name'] = $request->input('name');
    }

    $dog = DB::table('dogs')
        ->where('id', $id)
        ->update($data);

    return response()->json($dog);
});

Solution

  • It's not a good practise to get the whole request body and use that array to update the fields even if they have the same name.

    try below approach:

    $dog = DB::table('dogs')
            ->where('id', $request->route()->parameter('id'))
            ->update(['name' => $request->input('name')]);
    

    since the id matches that will solve your issue.

    Also since you mentioned postman keep in mind that you have to use the x-www-form-urlencode tab and not the normal form-data for PUT or PATCH actions.