PHP code example of ipunkt / laravel-json-api

1. Go to this page and download the library: Download ipunkt/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/ */

    

ipunkt / laravel-json-api example snippets


'providers' => [
	\Ipunkt\LaravelJsonApi\LaravelJsonApiServiceProvider::class,
]

'RelationshipFilterParser' => \Ipunkt\LaravelJsonApi\Services\RelationshipFilterParser\RelationshipFilterParserFacade::class,
'FilterApplier' => \Ipunkt\LaravelJsonApi\Services\FilterApplier\FilterApplierFacade::class,

'jwt.auth' => \Ipunkt\LaravelJsonApi\Http\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,

'api-content-type' => \Ipunkt\LaravelJsonApi\Http\Middleware\ContentTypeGuard::class,
'etag' => \Ipunkt\LaravelJsonApi\Http\Middleware\ETagMiddleware::class,

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
	'api' => [
		'api-content-type',
		'etag',
	],

	'secure-api' => [
		'api-content-type',
		'etag',
	],
];

public function boot(ResourceManager $resourceManager)

//  define in api version 1 a resource called 'posts'
$resourceManager->version(1)
    ->define('posts', function (ResourceDefinition $resource) {
        $resource->setRepository(PostRepository::class)
            ->setSerializer(PostSerializer::class);
    });

//  define in api version 1 a resource called 'posts'
$resourceManager->version(1)
    ->define('posts', function (ResourceDefinition $resource) {
        $resource->setRepository(PostRepository::class)
            ->setSerializer(PostSerializer::class)
            ->setRequestHandler(PostRequestHandler::class);
    });

class PostSerializer extends \Ipunkt\LaravelJsonApi\Serializers\Serializer
{
	/**
	 * resource type in response, can differ from requesting resource name
	 * @var string
	 */
	protected $type = 'posts';

	/**
     * returns links
     *
     * @param Model|Post $model
     * @return array
     */
    public function getLinks($model) : array
    {
        return [
            'comments' => 'https://localhost/api/v1/posts/1/comments',
        ];
    }

    /**
     * returns attributes for model
     *
     * @param Model|Post $model
     * @return array
     */
    protected function attributes($model) : array
    {
        return [
            'title' => $model->title,
            'slug' => str_slug($model->title),
            'content' => $model->content,
            'excerpt' => substr($model->content, 0, 200),
            'words' => count(explode(' ', $model->content)), //  example to show you can return more than only concrete model attributes
        ];
    }
}

class PostRepository extends \Ipunkt\LaravelJsonApi\Repositories\Repository
{
	/**
     * default sort criteria, when nothing given (can be empty)
     *
     * Format: 'fieldName' => 'asc', // or 'desc'
     *
     * @var array
     */
    protected $defaultSortCriterias = [
        'publish_datetime' => 'desc'
    ];

    /**
     * sort criterias (can be empty)
     *
     * Format: 'attributeNameInRequest' => 'field_name_in_database'
     * Example: 'date' in request will be 'publish_datetime' in sql query
     *
     * @var array
     */
    protected $sortCriterias = [
        'date' => 'publish_datetime',
    ];

    /**
     * constructor.
     * @param Model|Post $post
     * @param \Ipunkt\LaravelJsonApi\Repositories\Conditions\ConditionApplier $conditionApplier
     */
    public function __construct(Post $post, \Ipunkt\LaravelJsonApi\Repositories\Conditions\ConditionApplier $conditionApplier)
    {
        $this->model = $post;
        $this->conditionApplier = $conditionApplier;
    }
}

class PostRequestHandler extends \Ipunkt\LaravelJsonApi\Http\RequestHandlers\DefaultRequestHandler implements NeedsAuthenticatedUser
{

}

if ($request->expectsJson() ||
	$request->headers->contains('accept', ApiRequestHandler::CONTENT_TYPE)) {
	$error = new JsonApiError($exception->getMessage());

	if ($exception->getCode() > 100) {
		$error->setCode($exception->getCode());
	}

	if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundHttpException) {
		$error->setStatusCode(404)
			->setTitle('Resource not found');
	}

	if ($exception instanceof AuthorizationException) {
		$error->setStatusCode(403)
			->setTitle('Access forbidden');
	}

	if ($exception instanceof ValidationException) {
		$validationErrors = collect();
		foreach ($exception->validator->errors()->keys() as $key) {
			$validationErrors->push([
				'pointer' => $key,
				'message' => str_replace('attributes.', '', $exception->validator->errors()->first($key)),
			]);
		}
		$error->setSource($validationErrors);
	}

	if ($exception instanceof HttpExceptionInterface) {
		$error->setStatusCode($exception->getStatusCode());
	}

	if (app()->environment('local')) {
		$error->setException($exception);
	}

	return response()->json(['errors' => [$error]], $error->getStatusCode());
}

if ($request->expectsJson() ||
	$request->headers->contains('accept', ApiRequestHandler::CONTENT_TYPE)) {
	$error = new JsonApiError('Unauthenticated');
	$error->setStatusCode(401);

	return response()->json(['errors' => [$error]], $error->getStatusCode());
}

namespace Tests;

use App\User;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Ipunkt\LaravelJsonApi\Testing\Concerns\ModifiesRequestHeaders;
use Ipunkt\LaravelJsonApi\Testing\Concerns\PreparesRequestBody;

abstract class TestCase extends BaseTestCase
{
	use PreparesRequestBody,
		ModifiesRequestHeaders;
	use CreatesApplication;

	/**
	 * creates a user and logs him in
	 *
	 * @return User
	 */
	protected function createUserAndLogin(): User
	{
		$user = factory(\App\User::class)->create();

		$response = $this->postJson('/public/v1/tokens', $this->createRequestModel('credentials', [
			'email' => $user->email,
			'password' => 'secret',
		]), $this->headers());

		$json = $response->decodeResponseJson();
		$token = array_get($json, 'data.id');

		$this->setToken($token); // you are loggedin

		// you can now overwrite all requests headers with calling $this->headers().

		return $user;
	}
}
shell
php artisan vendor:publish --provider="Ipunkt\LaravelJsonApi\LaravelJsonApiServiceProvider"