1
votes

I'm studying api rest with laravel, I was able to implement all methods except PUT. Although the routes and controllers are correctly configured a response to a request using the PUT method is "laravel put Sorry, the page you are looking for could not be found.", As now image.

here is the method code in the controller in app/Http/Controllers/LivroController.php:

public function store(Request $request)  {

$livro = $request->isMethod('put') ? Livro::findOrFail($request->livro_id) : new Livro;

$livro->id = $request->input('livro_id');
$livro->nome = $request->input('nome');
$livro->descricao = $request->input('descricao');
$livro->user_id =  1; //$request->user()->id;

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

here is the route code in /routes/api.php:

Route::put('livro', 'LivroController@store');
3
is a get route working fine in api.php ? - Masoud Haghbin
yes the api has routes to get, post delete working. - Willer Silva de Morais

3 Answers

2
votes

If you want to create new data, you should use post method,

Route::post('livro', 'LivroController@store');

public function store(Request $request)  {

If you want to update exist data you should use put method,

Route::put('livro/{id}', 'LivroController@update');

public function update(Request $request, $id)  {

You can use this package https://github.com/durmus-aydogdu/laravel-resource for rest calls. This package highly customizable for rest and resource calls.

2
votes

change your postman method to POST and then add new parameter in your Body :

"_method" : PUT

This is because HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form

0
votes

Is better that you use controllers type resources and for this case the put method. Also you should validate the request. For example:

public function update(Request $request, $id)
{

  $livro = Livro::findOrFail($id);
  $validator = Validator::make($request->all(), [
    'livro_id' => 'required',
    'nome' => 'required',
    'descricao' => 'required',
  ]);
  if ($validator->fails()) {
    return response()->json(['errors'=>$validator->messages()],Response::HTTP_UNPROCESSABLE_ENTITY);
  }else{
    $livo->update($request->all());
    return response()->json(['livro'=>$livro], Response::HTTP_OK);
  }

}