Search code examples
phplaravellumen

How can I use JSON API Resource in a Lumen project?


In Laravel it can be done as simply as it is described here: https://laravel.com/docs/5.6/eloquent-resources.

Some says, API Resources is not meant for Lumen. However, just for the sake of this question, I want to know, strictly, if there is a way on how to add Laravel JSON API Resource in a Lumen project (the package use Illuminate\Http\Resources\Json\JsonResource; is missing from freshly created Lumen project).


Solution

  • API Resources are available in lumen, the files are there under: vendor\illuminate\http\Resources. what's missing is the artisan command to generate them. So just create the files manually, something like: app\Http\Resources\UserResource.php

    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class UserResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'name' => $this->name,
                'email' => $this->email,
            ];
        }
    }
    

    I don't know who says, API Resources is not meant for Lumen, but that's not true.