Search code examples
phplaravelrestlaravel-5laravel-5.5

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.


Solution

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