PHP code example of larsmbergvall / json-api-resources-for-laravel

1. Go to this page and download the library: Download larsmbergvall/json-api-resources-for-laravel 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/ */

    

larsmbergvall / json-api-resources-for-laravel example snippets


    public function books()
    {
        $books = Book::with(['author.country'])->take(2)->get();

        return JsonApiResourceCollection::make($books)->withIncluded();
    }

// ./app/Http/Kernel.php

protected $middlewareGroups = [
    // ...
    // Web middleware and such
    // ...
    'api' => [
        // Other api middlewares
        JsonApiMiddleware::class,
    ],
]

// ./routes/api.php

Route::prefix('/v1')
    ->middleware(JsonApiMiddleware::class)
    ->group(function () {
        // Api v1 routes
    });


use Larsmbergvall\JsonApiResourcesForLaravel\Attributes\JsonApiIncludeAttributes;
use Larsmbergvall\JsonApiResourcesForLaravel\Attributes\JsonApiIncludeRelationships;
use Larsmbergvall\JsonApiResourcesForLaravel\Attributes\JsonApiType;

#[JsonApiType('books')] // Change `type` property
#[JsonApiIncludeAttributes(['title', 'isbn', 'year'])] // Which of the models attributes to 

use Larsmbergvall\JsonApiResourcesForLaravel\JsonApi\JsonApiResource;

public function show(Book $book): JsonApiResource
{
    return JsonApiResource::make($book);
}

use Larsmbergvall\JsonApiResourcesForLaravel\JsonApi\JsonApiResourceCollection;

public function index(): JsonApiResource
{
    // Can also be used with pagination:
    // return JsonApiResourceCollection::make(Book::orderBy('title')->paginate());
    
    return JsonApiResourceCollection::make(Book::all());
}

// return jsonApiResponse(JsonApiResource::make($book));
return jsonApiResponse($content, $status, $headers)

$author = Author::factory()->create();
$resource = JsonApiResource::make($author);

$id = $author->id;
$type = 'author';
$resource->assertHasData($id, $type);

$author = Author::factory()->create();
$resource = JsonApiResourceCollection::make(collect([$author]));

$id = $author->id + 999;
$type = 'author';
$resource->assertDoesntHave($id, $type);