PHP code example of inna / think-api-resource

1. Go to this page and download the library: Download inna/think-api-resource library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

inna / think-api-resource example snippets




use Inna\ApiResource\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'posts' => PostResource::collection($this->whenLoad('posts')),
        ];
    }
}



use Inna\ApiResource\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
        ];
    }
}




class UserController 
{
    public function index()
    {
        $users = User::with('posts')->paginate();
      
        return UserResource::collection($users);
    }
    
    public function show()
    {
        $user = User::find(1);
      
        return UserResource::make($user)->wrap('user')->additional([
            'foo' => 'bar',
        ]);
    }
}