1. Go to this page and download the library: Download garbetjie/laravel-jsonapi 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/ */
garbetjie / laravel-jsonapi example snippets
use Garbetjie\Laravel\JsonApi\JsonApiResource;
use Garbetjie\Laravel\JsonApi\JsonApiResourceInterface;
use Illuminate\Http\Resources\MissingValue;
/**
* @property User $resource
*/
class UserResource extends JsonApiResource implements JsonApiResourceInterface
{
public function getJsonApiId() {
return $this->resource->getKey();
}
public function getJsonApiLinks($request) {
return new MissingValue();
}
public function getJsonApiMeta($request) {
return [
'loginCount' => 1,
'logoutCount' => new MissingValue(),
];
}
public function getJsonApiAttributes($request) {
return [
'name' => $this->resource->first_name,
'displayName' => trim("{$this->resource->first_name} {$this->resource->last_name}"),
'attribute' => $this->resource->has_attribute ? $this->resource->has_attribute : new MissingValue(),
];
}
public function getJsonApiType() {
return 'users';
}
public function getJsonApiRelationships($request) {
return [
'logins' => [
'data' => [
['type' => 'logins', 'id' => 1]
],
'links' => [
'related' => "/users/{$this->getJsonApiId()}/logins"
],
],
];
}
}
class UsersController extends Controller
{
public function index()
{
$user = User::findOrFail(1);
return new UserResource($user);
}
}
class User extends Model implements ConvertibleToJsonApiResourceInterface
{
public function convertToJsonApiResource() : JsonApiResourceInterface
{
return new UserResource($this);
}
}
class UsersController extends Controller
{
public function index()
{
return UserResource::collection(User::query()->all());
// or
return UserResource::collection(User::paginate(15));
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.