Search code examples
phplaravelrestful-architecture

Laravel 5.6 RESRful Webervice update and delete


I try to build a RESTful API in Laravel 5.6, now I also want do delete and update my database entrys with PUT and DELETE requests. If i use this code i get no error, I always get the messsage "Updated" or "Deleted" but de database never changes.

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \App\Car  $car
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $number)
{
    $bus = Bus::findOrFail($number);
    $bus->update($request->all());

    return response()->json(["message" => "Updated"]);
}

/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Car  $car
 * @return \Illuminate\Http\Response
 */
public function destroy($number)
{
    Bus::find($number)->delete();

    return response()->json(["message" => "Deleted"]);
}
}

routes/api.php

 Route::get('bus', 'BusController@index');
 Route::post('bus', 'BusController@store');
 Route::put('bus/{number}', 'BusController@update');
 Route::delete('bus/{number}', 'BusController@delete');

Solution

  • LARAVEL BLADE
    If you are working with Laravel blade, just add method_field (PUT/DELETE) with csrf_field at the beginning of form, something like the following:

    <form action="bus/<your_id_or_number>" method="post" enctype="multipart/form-data">
    
                {{ method_field('PUT') }}
                {{ csrf_field() }}
    
                ... rest of your code ...
    </form>
    

    POSTMAN API

    1. If you are testing your API on postman, change the API method to POST and add a new field/parameter with key=_method and value=PUT as in the following image:

    _method field

    2. or use x-www-form-urlencoded in body part with method type as default PUT/DELETE like:

    x-www-form-urlencoded