I am trying to create an API for my app so that I can share the endpoint and have one app as the core application with business logic and the other can connect with an exposed endpoint to consume the function as services.
I am getting an error when I try to hit the endpoint.
Below is my route/api.php
<?php
use App\PostModell;
use App\Http\Resources\PostModellResource;
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get( '/cars',function(){
return new PostModellResource(PostModell::all());
});
My resource class looks like
class PostModellResource extends Resource
{
public function toArray($request)
{
return
[
'id'=>$this->id,
'title'=>$this->title,
'body'=>$this->body,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
The error is
Sorry, the page you are looking for could not be found.
use api
prefix-
127.0.0.1:8000/api/cars
To convert collection of resources, you need to use collection() method-
return PostModellResource::collection(PostModell::all());
Since the route in api
routes, use this URI:
https://example.com/api/cars
Also, as I'm showing in my best practices repo you shouldn't put the logic into routes, move all the logic in a controller instead.
if you are using Laravel api.php
then you have to use api
prefix,
Or if your using Lumen web.php
then you can call it directly or you can define api prefix as per your requirement.
in Laravel : localhost:8000/api/yoururl
in Lumen : localhost/yoururl
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With