Error when using POST in Laravel API

Asked

Viewed 343 times

3

I’m learning how to build an API using Laravel 5.4.*.

In the Api.php:

$this->get('products', 'API\ProductController@index', ['except' => [
    'create', 'edit'
]]);

In the Product.php:

class Product extends Model
{
    protected $fillable = ['name', 'description'];
}

In the ProductController.php:

private $product;

public function __construct(Product $product)
{
    $this->product = $product;
}

public function index()
{
    $products = $this->product->all();

    return response()->json(['data' => $products]);
}

public function store(Request $request)
{
    return response()->json([
        'result' => $this->product->create($request->all())
    ]);
}

I reviewed my code and could not find errors.

When I use GET returns the registered products, but when I use POST I get this error:

inserir a descrição da imagem aqui

What can it be?

1 answer

3


Your code is correct and the error too :)

$this->get('products'

This route specifies that only requests through the get method will be processed otherwise it will be returned to http 405 method not allowed. Conceptually research is done through the get method, to create/add new features uses the post.

Recommended reading:

What are the advantages of using the right HTTP methods?

What is REST and Restful?

REST and HTTP are the same thing?

Rest api tutorial

Original article about Rest

API design - MS Guide

  • I created a $this->post('products', 'API\ProductController@store', ['except' => ['create', 'edit']]); and it worked, vlw even!

  • @Matthew put a complementary link, the idea of Rest is different from a normal web application.

  • I found an alternative to the >= 5.3 standard $this->resource('products', 'API\ProductController', ['except' => ['create', 'edit']]); and it already selects the appropriate method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.