PHP code example of gungcahyadipp / laravel-structured-response

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

    

gungcahyadipp / laravel-structured-response example snippets


use App\Http\Resources\UserResource;

return ok(UserResource::make($user));
return ok(UserResource::collection(User::paginate(15)));
return invalid($validator->errors());
return not_found('User not found');

use GungCahyadiPP\StructuredResponse\Http\Resources\JsonResource;

class UserResource extends JsonResource
{
    public function type(): string
    {
        return 'users';
    }

    public function attributes(): array
    {
        return [
            'name'  => $this->name,
            'email' => $this->email,
        ];
    }

    public function relationships(): array
    {
        return [
            'posts' => PostResource::collection($this->whenLoaded('posts')),
        ];
    }
}

return response_api()
    ->ok(UserResource::make($user))
    ->withMeta(['generated_at' => now()->toISOString()])
    ->send();

return ok(UserResource::collection(User::paginate(15)));

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(
        app(\GungCahyadiPP\StructuredResponse\Exceptions\ExceptionRenderer::class)->render(...)
    );
})

public function render($request, Throwable $e)
{
    $rendered = app(ExceptionRenderer::class)->render($request, $e);
    return $rendered ?? parent::render($request, $e);
}

use GungCahyadiPP\StructuredResponse\Testing\AssertableJsonResponse;

AssertableJsonResponse::from($response)
    ->assertResponseSuccess()
    ->assertResourceType('users')
    ->assertResourceCount(15)
    ->assertHasPagination();

use GungCahyadiPP\StructuredResponse\Support\ResponseBuilder;

ResponseBuilder::macro('accepted', fn () => $this->ok(null, 'Accepted'));
bash
php artisan vendor:publish --tag=structured-response-config