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:
What can it be?
I created a
$this->post('products', 'API\ProductController@store', ['except' => ['create', 'edit']]);
and it worked, vlw even!– Mateus
@Matthew put a complementary link, the idea of Rest is different from a normal web application.
– rray
I found an alternative to the >= 5.3 standard
$this->resource('products', 'API\ProductController', ['except' => ['create', 'edit']]);
and it already selects the appropriate method– Mateus