Laravel API Resource for API end point

May 16, 2018

I need to get the Json objects when I call the Get request http://myapp.com/api/products API end point

First thing you have do is create the normal controller using following artisan command

php artisan make:controller ProductController

And create the Product model too

Then you create the resource controller at App\Http\Resources location

 php artisan make:resource Product

Which will produce thw folllwong code

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Product extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

In your App\Http\Controllers\ProductController file you need to add following code

 
public function all(){
         header('Access-Control-Allow-Origin: *');
        return ProductResource::collection(Product::all());
    }

Add the followoing code below the namespace of this class

use App\Http\Resources\Plan as ProductResource;

Now you have to define api route. In you routes\api.php file you can add the following code

 
Route::get('/products', 'ProductController@all');