### Install Lomkit Laravel REST API Source: https://laravel-rest-api.lomkit.com/index Installs the Lomkit Laravel REST API package using Composer and initiates the quick start process to generate necessary files and configurations. ```bash composer require lomkit/laravel-rest-api php artisan rest:quick-start ``` -------------------------------- ### Install Laravel Rest API with Composer Source: https://laravel-rest-api.lomkit.com/getting-started/installation This command installs the Lomkit Laravel Rest API package using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your project's root directory. ```bash composer require lomkit/laravel-rest-api ``` -------------------------------- ### Quick Start API Generation Source: https://laravel-rest-api.lomkit.com/index Executes the quick start command to automatically generate all necessary files and configurations for a new Laravel REST API. ```bash php artisan rest:quick-start ``` -------------------------------- ### Publish Laravel Rest API Configuration Source: https://laravel-rest-api.lomkit.com/getting-started/installation This command publishes the configuration file for the Laravel Rest API package, allowing for customization. It uses the `php artisan vendor:publish` command with the `rest-config` tag. ```bash php artisan vendor:publish --tag=rest-config ``` -------------------------------- ### Get Resource Details (GET API) Source: https://laravel-rest-api.lomkit.com/endpoints/details Retrieves all necessary information to perform actions on a resource, reflecting the current state based on user permissions. The response includes available actions, instructions, fields, limits, scopes, relations, and validation rules. ```HTTP GET api/users ``` -------------------------------- ### Define Meta During Instruction Registration (PHP) Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This example shows how to attach meta information to an instruction when it's registered within a resource. This approach allows for defining distinct meta information based on the specific resource, providing flexibility in API response customization. ```PHP use App\Rest\Instructions\OddEvenIdInstruction; class UserResource extends Resource { /** * The instructions that should be linked * @param RestRequest $request * @return array */ public function instructions(RestRequest $request): array { return [ OddEvenIdInstruction::make() ->withMeta(['color' => '#FFFFFF']) ]; } } ``` -------------------------------- ### Laravel Rest API: Instruction with Fields Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to specify fields for a more complex instruction in Laravel Rest API. This example uses the 'odd-even-id' instruction with a 'type' field to specify 'odd' IDs. ```json { "search": { "instructions": [ { "name": "odd-even-id", "fields": [ {"field": "type", "value": "odd"} ] } ] } } ``` -------------------------------- ### Laravel Rest API: Basic Instruction Source: https://laravel-rest-api.lomkit.com/endpoints/search Shows how to specify a basic instruction for query operations in Laravel Rest API. This example uses the 'odd-even-id' instruction to retrieve posts with an even ID. ```json { "search": { "instructions": [ { "name": "odd-even-id" } ] } } ``` -------------------------------- ### Laravel Rest API: Specifying Gates Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to retrieve model permissions (gates) when querying data in Laravel Rest API. This example requests 'create' and 'view' permissions. ```json { "search": { "gates": ["create", "view"] } } ``` -------------------------------- ### Precognition Usage Example Source: https://laravel-rest-api.lomkit.com/digging-deeper/precognition This example demonstrates how to make a precognitive request to a Laravel Rest API endpoint. By setting the 'Precognition' header to 'true' and sending the request payload, the API will perform validation without executing controller logic, returning either a 422 error or a 204 success. ```HTTP POST /api/users/search Precognition: true Content-Type: application/json { "search": { // ... search parameters ... } } ``` -------------------------------- ### API Response Structure Source: https://laravel-rest-api.lomkit.com/endpoints/search Example of a typical API response containing filtered records and metadata, including pagination information and authorization gates. ```json { "current_page": 1, "data": [ { "id": 1, "name": "Lou West", "gates": { "authorized_to_view": true, "authorized_to_update": true, "authorized_to_delete": true, "authorized_to_restore": true, "authorized_to_force_delete": true } }, { "id": 2, "name": "Bridget Wilderman", "gates": { "authorized_to_view": true, "authorized_to_update": true, "authorized_to_delete": true, "authorized_to_restore": true, "authorized_to_force_delete": true } } ], "from": 1, "last_page": 1, "per_page": 50, "to": 2, "total": 2, "meta": { "gates": { "authorized_to_create": true } } } ``` -------------------------------- ### Laravel Rest API: Pagination and Limit Source: https://laravel-rest-api.lomkit.com/endpoints/search Shows how to control data retrieval using pagination and limit parameters in Laravel Rest API. This example specifies loading the second page with a limit of 10 items. ```json { "search": { "page": 2, "limit": 10 } } ``` -------------------------------- ### API Sorting Results Source: https://laravel-rest-api.lomkit.com/endpoints/search Provides examples of how to sort API results by one or more fields in ascending or descending order. ```json { "search": { "sorts": [ {"field": "user_id", "direction": "desc"}, {"field": "id", "direction": "asc"} ] } } ``` -------------------------------- ### Laravel Rest API: Aggregates with Filtering Source: https://laravel-rest-api.lomkit.com/endpoints/search Illustrates how to apply filters to aggregate calculations in Laravel Rest API. This example shows calculating the average 'stars' for 'comments' that are approved. ```json { "search": { "aggregates": [ { "relation": "comments", "type": "avg", "field": "stars", "filters": [ {"field": "approved", "value": true} ] } ] } } ``` -------------------------------- ### Define Post Policy for Attaching/Detaching Comments Source: https://laravel-rest-api.lomkit.com/digging-deeper/authorizations Example Laravel authorization policies for a Post model to control attaching and detaching Comment resources. It includes 'attachComment' and 'detachComment' methods. ```PHP is($model); } } ``` -------------------------------- ### Search Data with Laravel Rest API Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to use the search endpoint to query data with complex filtering, sorting, and inclusion criteria. This example showcases advanced features like nested filters, relationship inclusions with their own filters, and aggregates. ```JavaScript { "search": { "text": { "value": "my full text search" }, "scopes": [ {"name": "withTrashed", "parameters": [true]} ], "filters": [ { "field": "id", "operator": ">", "value": 1, "type": "or" }, { "nested": [ {"field": "user.id", "operator": "<", "value": 2}, {"field": "id", "operator": ">", "value": 100, "type": "or"} ] } ], "sorts": [ {"field": "user_id", "direction": "desc"}, {"field": "id", "direction": "asc"} ], "selects": [ {"field": "id"} ], "includes": [ { "relation": "posts", "filters": [ {"field": "id", "operator": "in", "value": [1, 3]} ], "limit": 2 }, { "relation": "user", "filters": [ { "field": "languages.pivot.boolean", "operator": "=", "value": true } ] } ], "aggregates": [ { "relation": "stars", "type": "max", "field": "rate", "alias": "approved_max_stars", "filters": [ {"field": "approved", "value": true} ] } ], "instructions": [ { "name": "odd-even-id", "fields": [ { "name": "type", "value": "odd" } ] } ], "gates": ["create", "view"], "page": 2, "limit": 10 } } ``` -------------------------------- ### Resource Hooks in Laravel Rest API Source: https://laravel-rest-api.lomkit.com/digging-deeper/hooks Illustrates the implementation of resource hooks in Laravel Rest API for reacting to model lifecycle events within resources. It provides an example of the `mutated` hook, showing how to access request data and the model to perform actions, such as saving an avatar image. ```PHP class UserResource extends Resource { public function mutated(MutateRequest $request, array $requestBody, Model $model): void { if ($requestBody['operation'] === 'update') { Storage::put('images/avatars/'.$model->getKey().'.jpg', $requestBody['attributes']['file']) } } } ``` -------------------------------- ### Upgrade Laravel Rest API: v1 to v2 Search Body Source: https://laravel-rest-api.lomkit.com/getting-started/upgrade-guide This snippet illustrates the required change in the API request body for the search endpoint when upgrading from Laravel Rest API v1 to v2. The primary change involves wrapping the existing filters within a new 'search' object. ```json // BEFORE // (POST) api/posts/search { "filters": [ { "field": "id", "operator": ">", "value": 1 } ] } ``` ```json // AFTER // (POST) api/posts/search { "search": { "filters": [ { "field": "id", "operator": ">", "value": 1 } ] } } ``` -------------------------------- ### Generate Instruction with Artisan Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This command generates a new instruction class, typically placed in `App\Rest\Instructions`. This class will be used to customize search queries. ```bash php artisan rest:instruction OddEvenIdInstruction ``` -------------------------------- ### API Routes Overview Source: https://laravel-rest-api.lomkit.com/index Displays a table of the generated API routes for the 'users' resource, including their HTTP methods, URIs, and names. ```bash +--------+----------------------------+-------------------+ | Method | URI | Name | +--------+----------------------------+-------------------+ | GET | api/users | api.users.details | | POST | api/users/search | api.users.search | | POST | api/users/actions/{action} | api.users.operate | | POST | api/users/mutate | api.users.mutate | | DELETE | api/users | api.users.destroy | +--------+----------------------------+-------------------+ ``` -------------------------------- ### PHP - Handle Scout Query Instructions Source: https://laravel-rest-api.lomkit.com/digging-deeper/full-text-search Implement the `handleScout` method within a custom instruction class to perform specific actions on the Scout query, allowing for tailored search logic. ```PHP /** * Perform the instruction on the scout query. * * @param array $fields * @param \Laravel\Scout\Builder $query * * @return void */ public function handleScout(array $fields, \Laravel\Scout\Builder $query) { // do something ... } ``` -------------------------------- ### Define Meta in Instruction Constructor (PHP) Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This snippet demonstrates how to define meta information directly within the constructor of a custom instruction class using the `withMeta` method. This is useful for setting default meta values that apply whenever the instruction is used. ```PHP class OddEvenIdInstruction extends Instruction { public function __construct() { $this->withMeta([ 'color' => '#FFFFFF' ]); } } ``` -------------------------------- ### Disable Authorizations for a Specific Resource Source: https://laravel-rest-api.lomkit.com/digging-deeper/authorizations Example of disabling authorizations for a specific resource, 'UserResource', by using the 'DisableAuthorizations' trait provided by Laravel Rest API. ```PHP class UserResource extends Resource { use \Lomkit\Rest\Concerns\Resource\DisableAuthorizations; // ... } ``` -------------------------------- ### Conditionally Expose Fields in Laravel Rest API Source: https://laravel-rest-api.lomkit.com/resources/exposed-data Allows for conditional exposure of fields based on user privileges. For example, exposing a 'password' field only to administrators. ```PHP public function fields(LomkitRestHttpRequestsRestRequest $request) { $fields = [ 'id', 'name' ]; if ($request->user()->isAdministrator()) { array_push($fields, 'password'); } return $fields; } ``` -------------------------------- ### Register Instruction in Resource Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This PHP code demonstrates how to register an instruction within a resource class by implementing the `instructions` method. It returns an array of instruction instances to be linked with the resource. ```php use App\Rest\Instructions\OddEvenIdInstruction; class UserResource extends Resource { /** * The instructions that should be linked * @param RestRequest $request * @return array */ public function instructions(RestRequest $request): array { return [ OddEvenIdInstruction::make() ]; } } ``` -------------------------------- ### Implement Instruction Logic Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This PHP code defines an `OddEvenIdInstruction` class that extends `Lomkit\Rest\Instructions\Instruction`. The `handle` method modifies the Eloquent query to filter by odd or even IDs based on the 'type' field, while the `fields` method defines the validation rules for the 'type' input. ```php namespace App\Rest\Instructions; use Illuminate\Database\Eloquent\Model; use Lomkit\Rest\Instructions\Instruction; use Lomkit\Rest\Http\Requests\RestRequest; class OddEvenIdInstruction extends Instruction { /** * Perform the instruction on the given query. * * @param array $fields * @param \Illuminate\Database\Eloquent\Builder $query * @return void */ public function handle(array $fields, \Illuminate\Database\Eloquent\Builder $query) { $number = match ($fields['type'] ?? 'even') { 'odd' => 1, default => 0, }; return $query ->whereRaw('MOD(id, 2) = '.$number); } /** * The instruction fields. * * @param \Lomkit\Rest\Http\Requests\RestRequest $request * @return array */ public function fields(\Lomkit\Rest\Http\Requests\RestRequest $request): array { return [ 'type' => [ 'string', 'in:odd,even' ] ]; } } ``` -------------------------------- ### Define Instruction Fields for Input Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This PHP code snippet focuses on the `fields` method within an instruction class. It defines the expected input fields and their validation rules, ensuring that data passed from the frontend is correctly validated before being used in the instruction's logic. ```php namespace App\Rest\Instructions; use Illuminate\Database\Eloquent\Model; use Lomkit\Rest\Instructions\Instruction; use Lomkit\Rest\Http\Requests\RestRequest; class OddEvenIdInstruction extends Instruction { /** * The instruction fields. * * @param \Lomkit\Rest\Http\Requests\RestRequest $request * @return array */ public function fields(\Lomkit\Rest\Http\Requests\RestRequest $request) { return [ 'type' => [ 'string', 'in:odd,even' ] ]; } } ``` -------------------------------- ### Conditionally Specify Limits in Laravel Rest API Source: https://laravel-rest-api.lomkit.com/resources/exposed-data Allows for dynamic specification of pagination limits based on user roles. For example, adding a 1000 limit for administrators. ```PHP public function limits(LomkitRestHttpRequestsRestRequest $request) { $limits = [ 10, 25, 50 ]; if ($request->user()->isAdministrator()) { array_push($limits, 1000); } return $limits; } ``` -------------------------------- ### Configure API Documentation (config/rest.php) Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This configuration snippet shows how to customize the API documentation using OpenApi specifications within the `config/rest.php` file. You can define information such as title, summary, description, contact details, license, and server URLs. This allows for detailed and accurate documentation of your API. ```php [ /* |-------------------------------------------------------------------------- | Rest Documentation |-------------------------------------------------------------------------- | | This is the feature that automatically generates your API documentation for you. | Laravel Rest Api will validate each searched / mutated / deleted model to avoid leaks in your API. | This feature is based on OpenApi, for more details see: https://swagger.io/specification/ | */ 'documentation' => [ 'info' => [ 'title' => config('app.name'), 'summary' => 'This is my projet\'s documentation', 'description' => 'Find out all about my projet\'s API', 'termsOfService' => null, // (Optional) Url to terms of services 'contact' => [ 'name' => 'My Company', 'email' => 'email@company.com', 'url' => 'https://company.com' ], 'license' => [ 'url' => null, 'name' => 'Apache 2.0', 'identifier' => 'Apache-2.0' ], 'version' => '1.0.0' ], // See https://spec.openapis.org/oas/v3.1.0#server-object 'servers' => [ [ 'url' => '/', // Relative to current 'description' => 'The current server' ], // [ // 'url' => '"https://my-server.com:{port}/{basePath}"', // 'description' => 'Production server', // 'variables' => [ // 'port' => [ // 'enum' => ['80', '443'], // 'default' => '443' // ], // 'basePath' => [ // 'default' => 'v2', // 'enum' => ['v1', 'v2'], // ] // ] // ] ], // See https://spec.openapis.org/oas/v3.1.0#security-scheme-object 'security' => [ // [ // 'type' => 'http', // 'description' => 'description', // 'scheme' => 'Bearer', // 'bearerFormat' => 'JWT' // ], // [ // 'type' => 'oauth2', // 'flows' => [ // 'authorizationCode' => [ // 'scopes' => ['write:pets'], // 'tokenUrl' => 'https://example.com/api/oauth/token', // 'authorizationUrl' => 'https://example.com/api/oauth/dialog', // 'refreshUrl' => 'https://example.com/api/oauth/refresh', // ] // ] // ] ] ] ] ``` -------------------------------- ### PHP - Define Scout Instructions in Resource Source: https://laravel-rest-api.lomkit.com/digging-deeper/full-text-search Customize Scout instructions within a resource by implementing the `scoutInstructions` method. This provides control over Scout's exposed instructions when the query handling differs. ```PHP /** * The scout fields that could be provided. * * @param RestRequest $request * * @return array */ public function scoutInstructions(RestRequest $request): array { return [ NumberedInstruction::make() ]; } ``` -------------------------------- ### Customize Authorization Cache Key in Laravel Rest API Source: https://laravel-rest-api.lomkit.com/digging-deeper/authorizations Example of overriding the 'getAuthorizationCacheKey' method in a resource class to customize how authorization cache keys are generated in Laravel Rest API. ```PHP class UserResource { /** * Get the authorization cache key. * * @param RestRequest $request * * @return string */ public function getAuthorizationCacheKey(RestRequest $request, string $identifier) { $class = Str::snake((new \ReflectionClass($this))->getShortName()); return sprintf( 'rest.authorization.%s.%s.%s', $class, $identifier, $request->user()?->getKey() ); } } ``` -------------------------------- ### Generate API Documentation (Artisan Command) Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This command generates the API documentation for your Laravel Rest API project. Ensure all desired routes are registered before running this command, as only exposed routes will appear in the documentation. The generated documentation is typically stored in the public folder and should be committed to version control. ```bash php artisan rest:documentation ``` -------------------------------- ### Implement Batchable Actions with Callbacks in PHP Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions Illustrates how to make actions batchable by implementing the `BatchableAction` and `ShouldQueue` interfaces. The `withBatch` method allows registering callbacks for batch completion, success, and failure. ```php namespace App\Rest\Actions; use Illuminate\Contracts\Queue\ShouldQueue; use Lomkit\Rest\Actions\Action; use Lomkit\Rest\Contracts\BatchableAction; use Illuminate\Bus\PendingBatch; use Illuminate\Bus\Batch; use Throwable; class SendWelcomeNotificationAction extends Action implements ShouldQueue, BatchableAction { /** * Register callbacks on the pending batch. * * @param array $fields * @param \Illuminate\Bus\PendingBatch $batch * @return void */ public function withBatch(array $fields, PendingBatch $batch) { $batch->then(function (Batch $batch) { // ... })->catch(function (Batch $batch, Throwable $e) { // ... })->finally(function (Batch $batch) { // ... }); } } ``` -------------------------------- ### Text Search with Trashed Models (JSON) Source: https://laravel-rest-api.lomkit.com/endpoints/search Example JSON payload for performing a text search that includes trashed records. The 'trashed' option is set to 'with' to include both non-trashed and trashed records. ```JSON { "search": { "text": { "value": "my text search", "trashed": "with" } } } ``` -------------------------------- ### Conditionally Register Instruction Source: https://laravel-rest-api.lomkit.com/digging-deeper/instructions This PHP code shows how to conditionally register an instruction based on user authorization. The `OddEvenIdInstruction` is only added to the list if the user is an administrator. ```php use App\Rest\Instructions\OddEvenIdInstruction; class UserResource extends Resource { /** * The instructions that should be linked * @param RestRequest $request * @return array */ public function instructions(RestRequest $request): array { $instructions = []; if ($request->user()->isAdministrator()) { array_push($instructions, OddEvenIdInstruction::make()) } return $instructions; } } ``` -------------------------------- ### Register Rest Documentation Service Provider Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This snippet demonstrates how to register the newly generated `RestDocumentationServiceProvider` in the `bootstrap/providers.php` file to enable custom route declarations. ```PHP return [ // ... App\Providers\RestDocumentationServiceProvider::class ]; ``` -------------------------------- ### Laravel Rest API: Aggregates with Alias Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to define a custom alias for an aggregate calculation in Laravel Rest API. This allows renaming the aggregate column in the response, for example, renaming 'average_stars'. ```json { "search": { "aggregates": [ { "relation": "comments", "type": "avg", "field": "stars", "alias": "average_stars" } ] } } ``` -------------------------------- ### Conditionally expose actions based on authorization Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions To restrict action visibility, you can add conditional logic within the resource's 'actions' method. This example shows how to only expose an action if the user is an administrator. ```PHP use App\Rest\Actions\SendWelcomeNotificationAction; class UserResource extends Resource { /** * The actions that should be linked * @param RestRequest $request * @return array */ public function actions(RestRequest $request): array { $actions = []; if ($request->user()->isAdministrator()) { array_push($actions, SendWelcomeNotificationAction::make()) } return $actions; } } ``` -------------------------------- ### Generate Rest Documentation Service Provider Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This command generates a new service provider class specifically for managing REST API documentation, which is a prerequisite for adding custom routes. ```Shell php artisan rest:documentation-provider ``` -------------------------------- ### Generate Users Controller Source: https://laravel-rest-api.lomkit.com/index Generates a controller for handling API requests related to users. This controller is linked to the previously defined UserResource. ```bash php artisan rest:controller UsersController ``` ```php resource`. ```PHP namespace App\Rest\Actions; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Lomkit\Rest\Actions\Action; use Lomkit\Rest\Http\Requests\RestRequest; class SendWelcomeNotificationAction extends Action { /** * Perform the action on the given models. * * @param array $fields * @param \Illuminate\Support\Collection $models * @return mixed */ public function handle(array $fields, \Illuminate\Support\Collection $models) { foreach ($models as $model) { $model->notify(new \App\Notifications\SendWelcomeNotification($fields['expires_at'])) ->delay($this->resource instanceof \App\Rest\UserResource ? 50 : 0); } } /** * The action fields. * * @param \Lomkit\Rest\Http\Requests\RestRequest $request * @return array */ public function fields(\Lomkit\Rest\Http\Requests\RestRequest $request) { return [ 'expires_at' => [ 'required', 'date' ] ]; } } ``` -------------------------------- ### Add Meta Information to Actions in PHP Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions Demonstrates how to add meta information to actions, which is exposed to frontend users. This can be done within the action's constructor using `withMeta` or during action registration for resource-specific meta data. ```php namespace App\Rest\Actions; use Lomkit\Rest\Actions\Action; class SendWelcomeNotificationAction extends Action { public function __construct() { $this->withMeta([ 'color' => '#FFFFFF' ]); } } ``` ```php namespace App\Rest\Actions; use App\Rest\Actions\SendWelcomeNotificationAction; use Lomkit\Rest\Http\Requests\RestRequest; use Lomkit\Rest\Resources\Resource; class UserResource extends Resource { /** * The actions that should be linked * @param RestRequest $request * @return array */ public function actions(RestRequest $request): array { return [ SendWelcomeNotificationAction::make() ->withMeta(['color' => '#FFFFFF']) ]; } } ``` -------------------------------- ### Perform Action with Fields Source: https://laravel-rest-api.lomkit.com/endpoints/actions Demonstrates how to perform an action by sending a POST request with specific fields, such as 'expires_at'. The response indicates the number of impacted models. ```HTTP POST api/users/actions/send-welcome-notification { "fields": [ { "name": "expires_at", "value": "2023-04-29" } ] } ``` ```JSON { "data": { "impacted": 150 } } ``` -------------------------------- ### Generate User Resource Source: https://laravel-rest-api.lomkit.com/resources/basics Generates a new resource file for a given model using the Artisan command. This is the first step in defining how your Eloquent models are exposed via the API. ```shell php artisan rest:resource UserResource ``` -------------------------------- ### Register API Routes Source: https://laravel-rest-api.lomkit.com/index Registers the API routes for the 'users' resource using the Lomkit REST facade. This defines the endpoints for various operations like fetching, searching, and mutating user data. ```php use \Lomkit\Rest\Facades\Rest; Rest::resource('users', \App\Rest\Controllers\UsersController::class) ``` -------------------------------- ### Generate User Resource Source: https://laravel-rest-api.lomkit.com/index Creates a new resource class for managing user data. This involves defining the resource and associating it with the corresponding Eloquent model. ```bash php artisan rest:resource UserResource ``` ```php */ public static $model = \App\Models\User::class; } ``` -------------------------------- ### Queue Actions with ShouldQueue Interface in PHP Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions Explains how to make actions queueable by implementing the `ShouldQueue` interface. This is useful for actions that require significant processing time, allowing Laravel to handle them asynchronously. ```php namespace App\Rest\Actions; use Illuminate\Contracts\Queue\ShouldQueue; use Lomkit\Rest\Actions\Action; class SendWelcomeNotificationAction extends Action implements ShouldQueue { // ... } ``` -------------------------------- ### Extend Route Operation in Controller Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This snippet shows how to extend a specific route operation (e.g., 'detail') within a controller to customize its OpenAPI documentation, such as adding custom tags. ```PHP namespace App\Rest\Controllers; use Lomkit\Rest\Documentation\Schemas\Operation; class UsersController { /** * Extend "detail" documentation operation * @param Operation $operation * @return Operation */ public function generateDocumentationDetailOperation(\Lomkit\Rest\Documentation\Schemas\Operation $operation): Operation { return $operation ->withTags(['my custom tag']); } } ``` -------------------------------- ### Customize Queue Connection and Name in PHP Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions Shows how to specify the queue connection and queue name for actions. By setting the `$connection` and `$queue` properties on the action class, you can direct queued actions to specific queues. ```php namespace App\Rest\Actions; use Illuminate\Contracts\Queue\ShouldQueue; use Lomkit\Rest\Actions\Action; class SendWelcomeNotificationAction extends Action implements ShouldQueue { /** * The name of the connection the job should be sent to. * * @var string|null */ public $connection; /** * The name of the queue the job should be sent to. * * @var string|null */ public $queue; } ``` -------------------------------- ### Resource Details Response Structure Source: https://laravel-rest-api.lomkit.com/endpoints/details The response provides a comprehensive JSON object detailing a resource's state. It includes a list of available actions with their URIs and required fields, instructions for operations, exposed fields, pagination limits, scope options, and relationship definitions. ```JSON { "data": { "actions": [ { "name": "Send Welcome Notification", "uriKey": "send-welcome-notification", "fields": { "delay": [ "required", "numeric" ] }, "meta": { "color": "#FFFFFF" }, "is_standalone": false } ], "instructions": [ { "name": "Odd Even Id", "uriKey": "odd-even-id", "fields": { "type": [ "in:odd,even" ] }, "meta": { "color": "#FFFFFF" } } ], "fields": [ "id", "name" ], "limits": [ 1, 10, 25, 50 ], "scopes": [ "withTrashed" ], "relations": [ { "resources": [ "App\\Rest\\Resources\\UserResource" ], "relation": "posts", "constraints": { "required_on_creation": false, "prohibited_on_creation": false, "required_on_update": false, "prohibited_on_update": false }, "name": "HasMany" } ], "rules": { "all": {"id": ["numeric"]}, "create": {"password": ["required"]}, "update": {"password": ["prohibited"]} } } } ``` -------------------------------- ### Laravel Rest API: Powerful Include with Filters Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to use the 'include' operation with custom filters and limits for more powerful data retrieval in Laravel Rest API. This allows specifying arguments like filters and limits for related resources. ```json { "search": { "includes": [ { "relation": "posts", "filters": [ {"field": "id", "operator": "in", "value": [1, 3]} ], "limit": 2 } ] } } ``` -------------------------------- ### Register an action in a resource Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions Actions are registered within a resource's 'actions' method. This makes the action available for the resource's endpoints. You can instantiate and return the action using `::make()`. ```PHP use App\Rest\Actions\SendWelcomeNotificationAction; class UserResource extends Resource { /** * The actions that should be linked * @param RestRequest $request * @return array */ public function actions(RestRequest $request): array { return [ SendWelcomeNotificationAction::make() ]; } } ``` -------------------------------- ### Generate a New Response Class Source: https://laravel-rest-api.lomkit.com/digging-deeper/responses Use the `rest:response` Artisan command to generate a new Response class. This command creates a boilerplate file in the `app/Rest/Responses` directory, ready for customization. ```bash php artisan rest:response UserResponse ``` -------------------------------- ### Generate a new action using Artisan Source: https://laravel-rest-api.lomkit.com/digging-deeper/actions This command generates a new action class for Laravel Rest API, placing it in the default 'App\Rest\Actions' directory. You can then customize the action's logic and fields. ```Shell php artisan rest:action SendWelcomeNotificationAction ``` -------------------------------- ### Perform Action with Complex Filtering Source: https://laravel-rest-api.lomkit.com/endpoints/actions Shows how to perform an action with complex filtering by including a 'search' argument with filters. This allows targeting specific models for the action. ```HTTP POST api/users/actions/send-welcome-notification { "fields": [ { "name": "expires_at", "value": "2023-04-29" } ], "search": { "filters": [ { "field": "has_received_welcome_notification", "value": false } ] } } ``` ```JSON { "data": { "impacted": 2 } } ``` -------------------------------- ### Declare Custom Routes in Service Provider Source: https://laravel-rest-api.lomkit.com/digging-deeper/documentation This snippet shows how to declare custom routes within the `RestDocumentationServiceProvider` using the `Rest::withDocumentationCallback` method, allowing for custom path definitions and operations. ```PHP use LaravelRestApi\OpenAPI; use LaravelRestApi\Path; use LaravelRestApi\Operation; // ... /** * Bootstrap any application services. * * @return void */ public function boot() { Rest::withDocumentationCallback(function (OpenAPI $openAPI) { $openAPI->withPaths( [ 'myPath' => (new Path) ->withDescription('my custom path') ->withGet( (new Operation) ->withTags(['Callable']) ->withSummary('You should call this !') ) ] ); return $openAPI; }); } ``` -------------------------------- ### API Selecting Specific Columns Source: https://laravel-rest-api.lomkit.com/endpoints/search Demonstrates how to specify which columns to retrieve in an API request to optimize performance. ```json { "search": { "selects": [ {"field": "id"}, {"field": "title"} ] } } ``` -------------------------------- ### Define Resource Model Source: https://laravel-rest-api.lomkit.com/resources/basics Specifies the Eloquent model that a Rest resource corresponds to. This property links the resource definition to your application's data models. ```php public static $model = 'App\Models\User'; ``` -------------------------------- ### Register Resource with Soft Deletes Source: https://laravel-rest-api.lomkit.com/resources/basics Registers a resource and enables soft delete routes, allowing for the restoration and force deletion of entries. ```php use \Lomkit\Rest\Facades\Rest; Rest::resource('users', \App\Rest\Controllers\UsersController::class)->withSoftDeletes() ``` -------------------------------- ### API Including Relationships Source: https://laravel-rest-api.lomkit.com/endpoints/search Shows how to eager load related data in API requests to reduce the number of database queries. ```json { "search": { "includes": [ { "relation": "posts" } ] } } ``` -------------------------------- ### Create User Post Relation Source: https://laravel-rest-api.lomkit.com/endpoints/mutate Demonstrates how to create a new post and associate it with a user, including creating a related 'star' entry for the post. This operation targets the `api/users/mutate` endpoint. ```json // (POST) api/users/mutate { "mutate": [ { "operation": "update", "key": 1, "relations": { "posts": [ { "operation": "create", "attributes": { "title": "My Post" }, "relations": { "star": { "operation": "create", "attributes": {"number": 2} } } }, ] } } ] } ``` -------------------------------- ### Register Resource in api.php Source: https://laravel-rest-api.lomkit.com/resources/basics Registers a resource with a specific API endpoint in the `api.php` file. This makes the resource accessible via HTTP requests. ```php use \Lomkit\Rest\Facades\Rest; Rest::resource('users', \App\Rest\Controllers\UsersController::class); ``` -------------------------------- ### Specify Resource in Controller Source: https://laravel-rest-api.lomkit.com/resources/basics Assigns the corresponding resource class to the controller. This tells the controller which resource it should operate on. ```php /** * The resource the controller corresponds to. * * @var class-string<\Lomkit\Rest\Http\Resource> */ public static $resource = App\Rest\Resources\UserResource::class; ``` -------------------------------- ### Register Resource with Specific Soft Deletes Source: https://laravel-rest-api.lomkit.com/resources/basics Registers a resource and enables specific soft delete routes (forceDelete, restore), excluding others. ```php use \Lomkit\Rest\Facades\Rest; Rest::resource('users', \App\Rest\Controllers\UsersController::class)->withSoftDeletes(['forceDelete', 'restore']) ```