fake-fakers / laravel-api-components
Set of useful Laravel components
1.0.1
2020-10-29 20:22 UTC
Requires
- php: >=7.2
- ext-json: *
- laravel/framework: 5.6.*|5.7.*|5.8.*|6.*|7.*|8.*
- symfony/psr-http-message-bridge: ~1.0
This package is not auto-updated.
Last update: 2024-05-25 14:10:31 UTC
README
Components list
Middleware
PreferJson
- a simple middleware that can be used in api routes, to prefer JSON-responses instead of default HTML. Also has an option to force JSON output even if Accept header is present.
Helper functions
formatValidationErrors
- transforms ValidationException to array.escapeStringForSqlLike
- escape string to use it in SQL LIKE queries.
Exceptions handler
Provides a simple way to define application exception handlers.
Usage:
- Inherit
app/Exception/Handler.php
class from exception handler from this package:use Brainex\ApiComponents\Exceptions\BaseHandler; class Handler extends BaseHandler { // write your code here }
- Define your own exception handlers:
/** * A list of custom exception handlers * * @return array */ protected function getCustomHandlers(): array { return [ OAuthServerException::class => [$this, 'oauthServerJson'] ]; } /** * Get JsonResponse for OAuthServerException exception * * @param OAuthServerException $exception * @return JsonResponse */ protected function oauthServerJson(OAuthServerException $exception): JsonResponse { return \response()->json([ 'message' => $exception->getErrorType(), 'data' => [ 'description' => $exception->getMessage(), 'hint' => $exception->getHint() ] ], $exception->getHttpStatusCode(), $exception->getHttpHeaders()); }
Service provider
RoutingServiceProvider
- overriding Laravel's default Router and ResponseFactory to return JSON responses withJSON_UNESCAPED_UNICODE
.
Usage:- Create
Application
class in your app folder:declare(strict_types=1); namespace App; use Illuminate\Log\LogServiceProvider; use Illuminate\Events\EventServiceProvider; /** * Class Application * @package App * * Overriding original application to hook router */ class Application extends \Illuminate\Foundation\Application { /** * Register all of the base service providers. * * @return void */ protected function registerBaseServiceProviders(): void { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); // hook responses to make them JSON_UNESCAPED_UNICODE $this->register(new \Brainex\ApiComponents\Routing\RoutingServiceProvider($this)); } }
- Patch
bootstrap/app.php
file to create newApplication
class instead of Laravel's default:$app = new \App\Application( realpath(__DIR__.'/../') );
- Create