1. Go to this page and download the library: Download gravure/laravel-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/ */
gravure / laravel-json-api example snippets
Gravure\Api\Providers\ApiProvider::class,
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function author()
{
return $this->belongsTo(User::class);
}
}
namespace App\Serializers;
use Gravure\Api\Resources\Collection;
use Tobscure\JsonApi\AbstractSerializer;
use Tobscure\JsonApi\Relationship;
use Tobscure\JsonApi\Resource;
class PostSerializer extends AbstractSerializer
{
protected $type = 'posts';
public function getId($model)
{
return $model->id;
}
public function getAttributes($model, array $fields = null)
{
return [
'title' => $model->title,
'content' => $model->content,
];
}
public function comments($model)
{
return new Relationship(new Collection($model->comments, new CommentSerializer));
}
public function author($model)
{
return new Relationship(new Resource($model->user, new UserSerializer));
}
}
namespace App\Repositories;
use App\Post;
use Gravure\Api\Contracts\Repository;
use Gravure\Api\Http\Request;
use Illuminate\Database\Eloquent\Model;
class PostRepository implements Repository
{
public function query()
{
return Post::query();
}
public function find(int $id): ?Model
{
return Post::find($id);
}
public function update(Model $model, Request $request): ?Model
{
$model->title = $request->get('title');
$model->content = $request->get('content');
$model->save();
return $model;
}
public function store(Request $request): ?Model
{
$model = new Post;
$model->title = $request->get('title');
$model->content = $request->get('content');
$model->save();
return $model;
}
public function delete(int $id): bool
{
$model = $this->find($id);
if ($model) {
return $model->delete();
}
return false;
}
}
namespace App\Http\Controllers;
use App\Repositories\PostRepository;
use App\Serializers\PostSerializer;
use Gravure\Api\Contracts\Repository;
use Gravure\Api\Controllers\ResourceController;
use Gravure\Api\Http\Request;
class PostController extends ResourceController
{
public function __construct(Request $request)
{
$this->request = $request;
$this->serializer = new PostSerializer();
}
protected function repository(): Repository
{
return new PostRepository();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.