Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 419
DENNIS KITHINJI Avatar asked Jan 24 '18 07:01

DENNIS KITHINJI


3 Answers

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());
like image 124
Sohel0415 Avatar answered Nov 17 '22 11:11

Sohel0415


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.

like image 39
Alexey Mezenin Avatar answered Nov 17 '22 13:11

Alexey Mezenin


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

like image 1
Vicky Gill Avatar answered Nov 17 '22 12:11

Vicky Gill