DENNIS KITHINJI
DENNIS KITHINJI

Reputation: 236

laravel 5.5 resource restful API

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.

Upvotes: 6

Views: 1061

Answers (4)

Sohel0415
Sohel0415

Reputation: 9853

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());

Upvotes: 3

Jag
Jag

Reputation: 131

All routes in the api have the prefix path of /api (by default). So in your case, you should access it via: http://YOURAPPURL/api/cars

You might want to check your App\Providers\RouteServiceProvider@mapApiRoutes for more information.

Upvotes: 1

Vicky Gill
Vicky Gill

Reputation: 734

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

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

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.

Upvotes: 3

Related Questions