1. Go to this page and download the library: Download timacdonald/json-api 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/ */
timacdonald / json-api example snippets
namespace App\Http\Controllers;
use App\Http\Resources\UserResource;
use App\Models\User;
class UserController
{
public function index()
{
$users = User::with([/* ... */])->paginate();
return UserResource::collection($users);
}
public function show(User $user)
{
$user->load([/* ... */]);
return UserResource::make($user);
}
}
namespace App\Http\Resources;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
//
}
namespace App\Http\Resources;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
public $attributes = [
'name',
'website',
'twitter_handle',
];
}
namespace App\Http\Resources;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
public $attributes = [
'name',
'website',
'twitter_handle',
];
public $relationships = [
'team' => TeamResource::class,
'posts' => PostResource::class,
];
}
namespace App\Http\Resources;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
public $attributes = [
'name',
'website',
'twitter_handle',
];
public $relationships = [
'team',
'posts',
];
}
namespace App\Http\Controllers;
use App\Http\Resources\UserResource;
use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;
class UserController
{
public function index()
{
$users = QueryBuilder::for(User::class)
->allowedIncludes(['team', 'posts'])
->paginate();
return UserResource::collection($users);
}
public function show($id)
{
$user = QueryBuilder::for(User::class)
->allowedIncludes(['team', 'posts'])
->findOrFail($id);
return UserResource::make($user);
}
}
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use TiMacDonald\JsonApi\JsonApiResource;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
JsonApiResource::useMinimalAttributes();
// ...
}
}
namespace App\Http\Resources;
use Illuminate\Support\Facades\Http;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
/**
* @param \Illuminate\Http\Request $request
* @return array<string, mixed>
*/
public function toAttributes($request)
{
return [
// ...
'avatar' => Http::get("https://avatar.example.com/{$this->id}")->body(),
];
}
}
namespace App\Http\Resources;
use Illuminate\Support\Facades\Http;
use TiMacDonald\JsonApi\JsonApiResource;
class UserResource extends JsonApiResource
{
/**
* @param \Illuminate\Http\Request $request
* @return array<string, mixed>
*/
public function toAttributes($request)
{
return [
// ...
'avatar' => fn () => Http::get("https://avatar.example.com/{$this->id}")->body(),
];
}
}