laravel-api-components maintained by fake-fakers
Description
Set of useful Laravel components
Author
Last update
2020/10/29 21:22
(dev-master)
License
Downloads
7
Laravel Api Components
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.phpclass 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
Applicationclass 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.phpfile to create newApplicationclass instead of Laravel's default:$app = new \App\Application( realpath(__DIR__.'/../') );
- Create