### Quick Authentication Setup Command Source: https://laravel-restify.com/docs/auth/authentication Run this command for a complete authentication setup on Laravel 11+. It installs Sanctum, configures the user model, and adds authentication routes. ```bash php artisan restify:setup-auth ``` -------------------------------- ### Install Sanctum and Migrate Source: https://laravel-restify.com/docs/auth/authentication Commands to install Laravel Sanctum and apply necessary database migrations. This is part of the manual setup process. ```bash composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate ``` -------------------------------- ### Run Laravel Restify Setup Command Source: https://laravel-restify.com/ Execute this Artisan command after installation to scaffold the API structure, publish configuration files, and generate necessary files and directories. ```shell php artisan restify:setup ``` -------------------------------- ### Install Lighthouse GraphQL Source: https://laravel-restify.com/docs/graphql/graphql-generation Install the necessary Lighthouse GraphQL package using Composer. This is a prerequisite for schema generation. ```bash composer require pusher/pusher-php-server lighthouse/lighthouse ``` -------------------------------- ### Install GraphQL Dependencies Source: https://laravel-restify.com/docs/graphql/graphql Install the necessary packages for GraphQL integration using Composer. ```bash composer require pusher/pusher-php-server lighthouse/lighthouse ``` -------------------------------- ### Minimal Repository Example Source: https://laravel-restify.com/docs/api/repositories-basic A minimal example of a repository class defining fields for API exposure. ```APIDOC ## Minimal Repository Example Here is a basic `PostRepository` that defines the fields to be exposed via the API. ```php namespace App\Restify; use App\Models\Post; use Binaryk\LaravelRestify\Repositories\Repository; use Binaryk\LaravelRestify\Http\Requests\RestifyRequest; use Binaryk\LaravelRestify\Attributes\Model; #[Model(Post::class)] class PostRepository extends Repository { public function fields(RestifyRequest $request): array { return [ field('title')->required(), field('content'), field('published_at')->nullable(), ]; } } ``` ``` -------------------------------- ### Store Request Response Example Source: https://laravel-restify.com/docs/api/repositories Example response after a successful store request, including the created entity's data and meta information. ```json { "data": { "id": "91ad557d-5780-4e4b-bedc-c35d400d8594", "type": "posts", "attributes": { "title": "Beautiful day!", "description": "Comming soon..." }, "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": false, "authorizedToDelete": false } } } ``` -------------------------------- ### AI Agent User Setup - Create and Assign Role Source: https://laravel-restify.com/docs/auth/authorization Demonstrates creating a dedicated user account for an AI agent and assigning it a specific role. This is a one-time setup for AI agent accounts. ```php // Create AI agent user $aiUser = User::create([ 'name' => 'Claude AI Agent', 'email' => 'claude@ai.example.com', 'password' => Hash::make('secure-password'), 'email_verified_at' => now(), ]); // Assign specific role for AI operations $aiUser->assignRole('ai-agent'); // Or assign specific permissions $aiUser->givePermissionTo(['read-posts', 'create-posts', 'update-own-posts']); ``` -------------------------------- ### Index Tool Example Source: https://laravel-restify.com/docs/mcp/repositories This example demonstrates how a repository definition in Restify leads to a generated MCP index tool for retrieving paginated lists of records with various query parameters. ```APIDOC ## Index Tool ### Description Retrieve a paginated list of Organization records from the organizations repository with filtering, sorting, and search capabilities. ### Method GET ### Endpoint /organizations ### Parameters #### Query Parameters - **page** (number) - Optional - Page number for pagination. - **perPage** (number) - Optional - Number of organizations per page. - **include** (string) - Optional - Comma-separated list of relationships to include with optional field selection. Supports nested relationships and field selection at each level. - **search** (string) - Optional - Search term to filter organizations by name or description. Available searchable fields: name. - **sort** (string) - Optional - Sorting criteria for the organizations. Available options: organizations.id, name (e.g., sort=field or sort=-field for descending). - **tags** (string) - Optional - Filter organizations resource by tags. Accepts exact match or negation (e.g., tags=some_value or -tags=some_value). - **address** (string) - Optional - Filter organizations resource by address. Accepts exact match or negation (e.g., address=some_value or -address=some_value). - **city** (string) - Optional - Filter organizations resource by city. Accepts exact match or negation (e.g., city=some_value or -city=some_value). - **country** (string) - Optional - Filter organizations resource by country. Accepts exact match or negation (e.g., country=some_value or -country=some_value). ### Response #### Success Response (200) - **data** (array) - List of organization records. - **meta** (object) - Pagination metadata. #### Response Example { "data": [ { "id": 1, "name": "Example Org", "address": "123 Main St", "city": "Anytown", "country": "USA", "users": [], "teams": [], "tags": [] } ], "meta": { "current_page": 1, "per_page": 10, "total": 1 } } ``` -------------------------------- ### Store Tool Example Source: https://laravel-restify.com/docs/mcp/repositories Create a new Post record. ```APIDOC ## Store Tool Example ### Description Create a new Post record. ### Input Schema ```json { "type": "object", "properties": { "title": { "type": "string", "description": "Title field for posts" }, "content": { "type": "string", "description": "Content field for posts" }, "status": { "type": "string", "description": "Status field for posts" }, "category": { "type": "string", "description": "Category field for posts" } }, "required": [ "title" ] } ``` ``` -------------------------------- ### Run Database Migrations Source: https://laravel-restify.com/ Complete the setup by running database migrations to create any necessary tables for Restify. ```shell php artisan migrate ``` -------------------------------- ### Token TTL Configuration Examples Source: https://laravel-restify.com/docs/auth/authentication Examples demonstrating how to set the token expiration time (token_ttl) in minutes. Set to null for tokens that never expire. ```php // Examples 'token_ttl' => null, // Never expire (default) 'token_ttl' => 30, // 30 minutes 'token_ttl' => 60, // 1 hour 'token_ttl' => 1440, // 24 hours ``` -------------------------------- ### Example Repository Generation Output Source: https://laravel-restify.com/docs/api/repository-generation This output shows the detected repository pattern and the target directory for the new repository. It confirms successful creation. ```bash $ php artisan restify:repository PostRepository Detected repository pattern: grouped-by-model Repository will be created in: App\Restify Repository created successfully. ``` -------------------------------- ### Discover Repositories Tool (Wrapper Mode) Source: https://laravel-restify.com/docs/mcp/mcp Example request and response for the `discover-repositories` tool used in Wrapper Mode for MCP integration. ```APIDOC ### The 4 Wrapper Tools When using wrapper mode, AI agents use these 4 tools in a progressive discovery workflow: #### 1. `discover-repositories` Lists all available MCP-enabled repositories with metadata. Supports optional search filtering. **Example Request:** ```json { "search": "user" } ``` **Example Response:** ```json { "success": true, "repositories": [ { "name": "users", "title": "Users", "description": "Manage user accounts", "operations": ["index", "show", "store", "update", "delete", "profile"], "actions_count": 2, "getters_count": 1 } ] } ``` ``` -------------------------------- ### Update Request Response Example Source: https://laravel-restify.com/docs/api/repositories Example response after a successful update request, showing the modified entity data and updated meta information. ```json { "data": { "id": "91ad557d-5780-4e4b-bedc-c35d400d8594", "type": "posts", "attributes": { "title": "Beautiful day!", "description": "Ready to be published!" }, "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": true, "authorizedToDelete": false } } } ``` -------------------------------- ### Direct Mode Configuration Source: https://laravel-restify.com/docs/mcp/mcp Configuration example for enabling Direct Mode in MCP integration via the `.env` file. ```APIDOC ### Direct Mode (Default) **Configuration:** ```dotenv RESTIFY_MCP_MODE=direct ``` ``` -------------------------------- ### Discover Repositories Tool Response Source: https://laravel-restify.com/docs/mcp/mcp Example JSON response from the `discover-repositories` tool, detailing available repositories, their operations, and counts. ```json { "success": true, "repositories": [ { "name": "users", "title": "Users", "description": "Manage user accounts", "operations": ["index", "show", "store", "update", "delete", "profile"], "actions_count": 2, "getters_count": 1 } ] } ``` -------------------------------- ### Install Laravel Restify Boost Source: https://laravel-restify.com/docs/boost/boost Install the Boost package as a development dependency using Composer. ```bash composer require --dev binarcode/laravel-restify-boost ``` -------------------------------- ### Bulk Store Payload Example Source: https://laravel-restify.com/docs/api/repositories Example payload for a bulk store request, containing an array of objects to be created. ```json [ { "title": "Post 1", "description": "Description post 1" }, { "title": "Post 2", "description": "Description post 2" } ] ``` -------------------------------- ### Using Search, Filters, and Sorting Source: https://laravel-restify.com/docs/api/repositories-basic Examples of how to use query parameters to search, filter, and sort repository resources. ```APIDOC ### Using Search and Filters ```http # Search for posts containing "laravel" GET /api/restify/posts?search=laravel # Filter by status GET /api/restify/posts?status=published # Sort by title GET /api/restify/posts?sort=title # Sort descending GET /api/restify/posts?sort=-title # Combine multiple parameters GET /api/restify/posts?search=laravel&status=published&sort=-created_at ``` ``` -------------------------------- ### Generated UserRepository Example Source: https://laravel-restify.com/docs/api/repository-generation An example of a generated repository class for the User model. It defines the model and its fields, including special handling for email and timestamps. ```php email(), field('email_verified_at')->datetime()->readonly(), field('created_at')->datetime()->readonly(), field('updated_at')->datetime()->readonly(), ]; } } ``` -------------------------------- ### Wrapper Mode Configuration Source: https://laravel-restify.com/docs/mcp/mcp Configuration example for enabling Wrapper Mode in MCP integration via the `.env` file. ```APIDOC ### Wrapper Mode (Token-Efficient) **Configuration:** ```dotenv RESTIFY_MCP_MODE=wrapper ``` ``` -------------------------------- ### Store Request Payload Example Source: https://laravel-restify.com/docs/api/repositories Example payload for a POST request to store a new entity. It includes the title and description for a post. ```json { "title": "Beautiful day!", "description": "Comming soon..." } ``` -------------------------------- ### Poor Example of Repository Description Source: https://laravel-restify.com/docs/mcp/repositories Avoid vague descriptions like 'CRUD operations' as they do not provide enough context for AI agents. ```php public static string $description = 'CRUD operations for subscriptions.'; ``` -------------------------------- ### Field Type Mapping Examples Source: https://laravel-restify.com/docs/api/repository-generation These examples illustrate how different database column types are automatically mapped to corresponding Restify field types. ```php field('name') ``` ```php field('email')->email() ``` ```php field('password')->password()->storable() ``` ```php field('description')->textarea() ``` ```php field('count')->number() ``` ```php field('is_active')->boolean() ``` ```php field('birth_date')->date() ``` ```php field('created_at')->datetime() ``` ```php field('price')->number() ``` ```php field('metadata')->json() ``` -------------------------------- ### Basic Repository Definition Source: https://laravel-restify.com/docs/api/repositories Example of defining a basic repository using attributes and the `fields` method. ```APIDOC ## Basic Repository Definition ### Description This example demonstrates how to define a repository for the `Post` model using the modern attribute approach and defining its fields. ### Code Example ```php namespace App\Restify; use App\Models\Post; use Binaryk\LaravelRestify\Repositories\Repository; use Binaryk\LaravelRestify\Http\Requests\RestifyRequest; use Binaryk\LaravelRestify\Attributes\Model; #[Model(Post::class)] class PostRepository extends Repository { public function fields(RestifyRequest $request): array { return [ field('title')->required(), field('content')->string(), field('published_at')->nullable(), ]; } } ``` ### Notes - If the model is not specified using an attribute or the `$model` property, Restify will attempt to guess the model based on the repository class name. - The `fields` method defines the attributes that will be applied during API requests. ``` -------------------------------- ### Basic Rule Conversion Example Source: https://laravel-restify.com/docs/mcp/json-schema-converter A simple PHP example showing the initial Laravel validation rules array that will be converted into JSON Schema. ```php $rules = [ 'event_date' => ['required', 'date', 'before:2025-12-31'], ]; ``` -------------------------------- ### MCP Configuration Source: https://laravel-restify.com/docs/mcp/mcp Example of the MCP-specific configuration options within the `config/restify.php` file. ```APIDOC ## Configuration The MCP integration respects your existing Restify configuration and adds MCP-specific options: ```php // config/restify.php 'mcp' => [ 'enabled' => true, 'server_name' => 'My App MCP Server', 'server_version' => '1.0.0', 'default_pagination' => 25, 'mode' => env('RESTIFY_MCP_MODE', 'direct'), // 'direct' or 'wrapper' 'tools' => [ 'exclude' => [ // Tools to exclude from discovery ], 'include' => [ // Additional tools to include ], ], ], ``` ``` -------------------------------- ### Flat Repository Structure Example Source: https://laravel-restify.com/docs/api/repository-generation This shows the default flat structure where all repositories are placed directly within the `app/Restify` directory. ```directory app/Restify/ ├── UserRepository.php ├── PostRepository.php └── CommentRepository.php ``` -------------------------------- ### AI Agent Usage Example for Stripe Information Getter Source: https://laravel-restify.com/docs/mcp/getters An example of how an AI agent would call the Stripe Information getter, providing the required 'id' and optional parameters to retrieve specific user data. ```json // Must provide the id { "id": "123", "include_invoices": true, "include_payment_methods": true } ``` -------------------------------- ### Simple Data Wrapper Response Source: https://laravel-restify.com/docs/api/serializer This example shows the output of the `data` helper, where the serialized user object is placed under the 'data' key. ```json { "data": { "id": 1, "name": "User name", "email": "kshlerin.hertha@example.com" } } ``` -------------------------------- ### Show Tool Example Source: https://laravel-restify.com/docs/mcp/repositories Retrieve a specific Organization record by ID with optional relationship loading. ```APIDOC ## Show Tool Example ### Description Retrieve a specific Organization record by ID with optional relationship loading. ### Input Schema ```json { "type": "object", "properties": { "id": { "type": "string", "description": "The ID of the organization to retrieve" }, "include": { "type": "string", "description": "Comma-separated list of relationships to include (e.g., include=users,teams,tags)" } }, "required": ["id"] } ``` ``` -------------------------------- ### Domains Repository Structure Example Source: https://laravel-restify.com/docs/api/repository-generation This demonstrates the domains structure where each repository is placed within its own subdirectory under `app/Restify/Domains`. ```directory app/Restify/Domains/ ├── User/ │ └── UserRepository.php ├── Post/ │ └── PostRepository.php └── Comment/ └── CommentRepository.php ``` -------------------------------- ### Good Example of Repository Description Source: https://laravel-restify.com/docs/mcp/repositories A good repository description is specific about the domain, mentions key capabilities, includes context, and is concise. ```php public static string $description = 'Manages user subscriptions and billing. Handles subscription creation, upgrades, downgrades, cancellations, and payment processing through Stripe. Each subscription is linked to a user and a pricing plan.'; ``` -------------------------------- ### AI Agent Usage for Show Actions Source: https://laravel-restify.com/docs/mcp/actions Example AI agent input for show actions, demonstrating the required 'id' parameter. ```json // Must provide the id { "id": "123" } ``` -------------------------------- ### Custom Store Method Implementation Source: https://laravel-restify.com/docs/api/repositories Example of overriding the default store method in a repository to implement custom logic. ```php public function store(RestifyRequest $request) { // } ``` -------------------------------- ### Production Setup with Domains Structure Source: https://laravel-restify.com/docs/api/repository-generation Generate repositories using a domains structure, skipping the preview, and forcing the overwrite. This is suitable for production environments. ```bash # Generate with domains structure, skip preview php artisan restify:generate:repositories \ --structure=domains \ --skip-preview \ --force ``` -------------------------------- ### AI Agent Usage for Default Actions Source: https://laravel-restify.com/docs/mcp/actions Example AI agent input for default actions, showing that the 'resources' array is still required. ```json // Still requires resources array (index behavior) { "resources": ["1", "2", "3"] } ``` -------------------------------- ### Example Response for Available Filters Source: https://laravel-restify.com/docs/search/advanced-filters Illustrates the JSON structure returned when requesting available filters, detailing each filter's properties and options. ```json { "data": [ { "key": "active-boolean-filter", "type": "boolean", "options": [ { "label": "Is Active", "property": "is_active" } ] }, { "key": "select-category-filter", "type": "select", "options": [ { "label": "Movie category", "property": "movie" }, { "label": "Article Category", "property": "article" } ] }, { "key": "created-after-date-filter", "type": "timestamp", "options": [] }, { "key": "email", "type": "value", "description": "Email", "label": "Email", "meta": { "operator": "like" } } ] } ``` -------------------------------- ### Practical Example: Full-text Search Source: https://laravel-restify.com/docs/api/fields Perform full-text searches on specified columns by using the `whereFullText` method within a closure passed to `searchable()`. ```php field('content')->searchable(function ($request, $query, $value) { $query->whereFullText(['title', 'description'], $value); }), ``` -------------------------------- ### Defining Repository Fields Source: https://laravel-restify.com/docs/api/repositories This example shows how to define fields for a Post repository, including rules, sortability, searchability, and visibility controls. ```APIDOC ## `fields(RestifyRequest $request): array` ### Description Defines the attributes of the model that will be exposed through the repository's endpoints. It's a best practice to expose the minimum necessary fields. ### Method `fields` ### Parameters - `request` (RestifyRequest) - The incoming request object. ### Returns An array of field definitions. ### Example ```php use Binaryk\LaravelRestify\Repositories\Repository; use Binaryk\LaravelRestify\Http\Requests\RestifyRequest; class PostRepository extends Repository { public function fields(RestifyRequest $request): array { return [ field('title') ->rules('required', 'max:255') ->sortable() ->matchable(), field('slug') ->rules('required', 'unique:posts,slug') ->hideFromIndex(), field('content') ->textarea() ->rules('required', 'min:100') ->searchable(), field('excerpt') ->nullable() ->hideFromIndex(), field('status') ->select(['draft', 'published', 'archived']) ->default('draft') ->sortable() ->matchable(), field('published_at') ->nullable() ->sortable(), field('featured') ->boolean() ->default(false) ->matchable(), ]; } } ``` ``` -------------------------------- ### Generate All Repositories with Preview Source: https://laravel-restify.com/docs/api/repository-generation Run the command without any flags to generate repositories for all models, including a preview. ```bash # Generate all repositories with preview php artisan restify:generate:repositories ``` -------------------------------- ### Show Endpoint Response Structure Source: https://laravel-restify.com/docs/api/repositories An example of the JSON response structure for a GET request to a show endpoint, including data, attributes, and meta information. ```APIDOC ## Show Request Response ### Description Represents the JSON response for a `GET` request to a specific resource endpoint (e.g., `/api/restify/posts/1`). ### Response Example ```json { "data": { "id": "1", "type": "posts", "attributes": { "title": "Amet ratione est quas quia ut nemo.", "description": null }, "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": false, "authorizedToDelete": false } } } ``` ``` -------------------------------- ### User Revenue Breakdown Getter Example Source: https://laravel-restify.com/docs/mcp/getters This getter provides a revenue breakdown for a specific user, allowing filtering by date range and currency. ```php class UserRevenueBreakdownGetter extends Getter { public string $description = 'Get revenue breakdown for a specific user by product and region'; public function rules(): array { return [ 'start_date' => ['required', 'date'], 'end_date' => ['required', 'date', 'after:start_date'], 'currency' => ['string', 'in:USD,EUR,GBP'], ]; } public function handle(Request $request, User $user) { $validated = $request->validate($this->rules()); return response()->json([ 'data' => $user->revenueBreakdown($validated), ]); } } ``` -------------------------------- ### Example Token Creation Flow Source: https://laravel-restify.com/docs/mcp/mcp Demonstrates the complete process of creating an MCP token, including selecting tools, generating the token, and storing it with permissions. The plain text token is returned once for the user. ```php use App\Models\McpToken; use Illuminate\Support\Str; // 1. Show available tools to user $server = app(RestifyServer::class); $availableTools = $server->getAllAvailableTools()->toSelectOptions(); // 2. User selects which tools to grant access to $selectedTools = [ 'users-index', 'users-show', 'posts-index', 'posts-store', 'posts-publish-action', ]; // 3. Generate the token $plainTextToken = Str::random(64); // 4. Store token with permissions $mcpToken = McpToken::create([ 'name' => 'AI Agent Token', 'token' => hash('sha256', $plainTextToken), 'allowed_tools' => $selectedTools, // Cast to JSON in model 'user_id' => auth()->id(), 'expires_at' => now()->addDays(30), ]); // 5. Return plain text token to user (only shown once) return response()->json([ 'token' => $plainTextToken, 'allowed_tools' => $selectedTools, ]); ``` -------------------------------- ### Create Test User in DatabaseSeeder Source: https://laravel-restify.com/docs/auth/authentication Example of creating a test user within the `DatabaseSeeder` class for testing authentication. Remember to hash the password. ```php \App\Models\User::factory()->create([ 'name' => 'Test User', 'email' => 'test@example.com', 'password' => \Illuminate\Support\Facades\Hash::make('password'), ]); ``` -------------------------------- ### Practical Example: Date Range Filtering Source: https://laravel-restify.com/docs/api/fields Filter records by a date range using `matchable()` with a closure. It parses comma-separated start and end dates to apply a `whereBetween` clause. ```php field('date_range')->matchable(function ($request, $query, $value) { [$start, $end] = explode(',', $value); $query->whereBetween('created_at', [$start, $end]); }), ``` -------------------------------- ### Successful Login Response Source: https://laravel-restify.com/docs/auth/authentication Example of a successful JSON response after logging in, including user details and an authentication token. ```json { "id": "11", "type": "users", "attributes": { "name": "Test User", "email": "test@example.com" }, "meta": { "authorizedToShow": true, "authorizedToStore": false, "authorizedToUpdate": false, "authorizedToDelete": false, "token": "1|f7D1qkALtM9GKDkjREKpwMRKTZg2ZnFqDZTSe53k" } } ``` -------------------------------- ### Get Operation Details Source: https://laravel-restify.com/docs/mcp/mcp Retrieve the full JSON schema and documentation for a specific repository operation. This includes parameters, validation rules, and examples. Requires repository name and operation type. ```json { "repository": "users", "operation_type": "store" } ``` -------------------------------- ### Practical Example: E-commerce Product Search Source: https://laravel-restify.com/docs/api/fields Implement a multi-column search for e-commerce products using a closure within `matchable()`. This filters by name, description, or SKU. ```php field('search')->matchable(function ($request, $query, $value) { $query->where(function ($q) use ($value) { $q->where('name', 'like', "%{$value}%") ->orWhere('description', 'like', "%{$value}%") ->orWhere('sku', 'like', "%{$value}%"); }); }), ``` -------------------------------- ### Zero Configuration Repository Setup Source: https://laravel-restify.com/ Define a repository class by specifying the associated Eloquent model. This is sufficient to enable full CRUD API functionality. ```php class UserRepository extends Repository { public static string $model = User::class; // That's it! Full CRUD API ready 🚀 } ``` -------------------------------- ### Example of PasswordUpdateInvokable Class Source: https://laravel-restify.com/docs/api/fields An example of an invokable class that can be used with `updateCallback` to handle password updates. ```php class PasswordUpdateInvokable { public function __invoke(Request $request) { return Hash::make($request->input('password')); } } ``` -------------------------------- ### Discover Repositories Tool Request Source: https://laravel-restify.com/docs/mcp/mcp Example JSON request for the `discover-repositories` tool in Wrapper Mode, used to list available MCP-enabled repositories with optional search filtering. ```json { "search": "user" } ``` -------------------------------- ### Lazy Loading Relationship Example Source: https://laravel-restify.com/docs/api/fields Demonstrates how a computed attribute like `profileTagNames` can be efficiently loaded by specifying the related `tags` relationship to be lazy-loaded. ```php field('profileTagNames', fn() => $this->model()->profileTagNames) ->lazy('tags') ``` -------------------------------- ### Update Request Payload Example Source: https://laravel-restify.com/docs/api/repositories Example payload for a PUT request to update an existing entity. Only the description is modified. ```json { "description": "Ready to be published!" } ``` -------------------------------- ### Basic File Storage Example Source: https://laravel-restify.com/docs/api/fields Illustrates the default behavior of storing an uploaded file using Laravel's filesystem. Ensure the 'public' disk is linked if using the local driver. ```php use Illuminate\Http\Request; Route::post('/avatar', function (Request $request) { $path = $request->avatar->store('/', 'public'); $request->user()->update([ 'avatar' => $path, ]); }); ``` -------------------------------- ### Store Validation Example Source: https://laravel-restify.com/docs/api/repositories Example of validating the 'description' field during a store operation using Laravel's validate method. ```php $request->validate([ 'description' => 'required', ]) ``` -------------------------------- ### User Activity Analytics Getter Example Source: https://laravel-restify.com/docs/mcp/getters This getter retrieves detailed activity analytics for a user, supporting period-based filtering and trend inclusion. ```php class UserActivityAnalyticsGetter extends Getter { public string $description = 'Get detailed activity analytics for a user'; public function rules(): array { return [ 'period' => ['required', 'in:7d,30d,90d'], 'include_trends' => ['boolean'], ]; } public function handle(Request $request, User $user) { $validated = $request->validate($this->rules()); return response()->json([ 'data' => $user->activityAnalytics($validated), ]); } } ``` -------------------------------- ### Example Generated GraphQL Schema Source: https://laravel-restify.com/docs/graphql/graphql This is an example of a GraphQL schema generated from a Restify repository, including types, inputs, queries, and mutations. ```graphql type User { id: ID! name: String email: String created_at: String updated_at: String } input UserInput { name: String email: String } type Query { user(id: ID!): User userList(first: Int = 15, page: Int = 1): [User!]! } type Mutation { createUser(input: UserInput!): User! updateUser(id: ID!, input: UserInput!): User! deleteUser(id: ID!): Boolean! } ``` -------------------------------- ### Customizing Entire Storage Process Source: https://laravel-restify.com/docs/api/fields Details how to take full control of the file storage logic using the `store` method with a callable. ```APIDOC ## Customizing The Entire Storage Process ### Description Provides full control over the file storage logic by using the `store` method with a callable that receives the incoming HTTP request and the model instance. ### Field Definition ```php use Illuminate\Http\Request; use Restify\Fields\File; File::make('avatar') ->store(function (Request $request, $model) { return [ 'attachment' => $request->attachment->store('/', 's3'), 'attachment_name' => $request->attachment->getClientOriginalName(), 'attachment_size' => $request->attachment->getSize(), ]; }) ``` ### Explanation The `store` callback returns an array of key/value pairs that are mapped onto the model's instance before saving to the database. ``` -------------------------------- ### Getting a Specific Post via API Source: https://laravel-restify.com/docs/api/repositories-basic Fetch a single post by its ID by sending a GET request to the specific post's endpoint. ```http GET /api/restify/posts/1 ``` -------------------------------- ### Get User Profile Source: https://laravel-restify.com/docs/auth/profile Use the GET /api/restify/profile endpoint to retrieve the authenticated user's profile. Authorization is required via a Bearer token. ```http GET: /api/restify/profile ``` ```curl curl -X GET "http://your-domain.com/api/restify/profile" \ -H "Accept: application/json" \ -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..." ``` -------------------------------- ### JSON:API Response Example Source: https://laravel-restify.com/docs/api/serializer This is an example of a JSON:API compliant response structure for a company with related users, including attributes, relationships, and meta information. ```json { "data": { "id": "1", "type": "companies", "attributes": { "name": "BinarCode" }, "relationships": { "users": [ { "id": "1", "type": "users", "attributes": { "name": "Eduard", "email": "eduard.lupacescu@binarcode.com" }, "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": true, "authorizedToDelete": true }, "pivots": { "is_admin": true } } ] }, "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": true, "authorizedToDelete": true } } } ``` -------------------------------- ### Numeric Bounds Rule Conversion Example Source: https://laravel-restify.com/docs/mcp/json-schema-converter A PHP example defining validation rules for a 'quantity' field, including required, integer type, and minimum/maximum value constraints. ```php $rules = [ 'quantity' => ['required', 'integer', 'min:1', 'max:100'], ]; ``` -------------------------------- ### Create a Repository Source: https://laravel-restify.com/ Define a repository by extending the `Repository` class and specifying the Eloquent model. ```php class PostRepository extends Repository { public static string $model = Post::class; } ``` -------------------------------- ### Creating a Repository Source: https://laravel-restify.com/docs/api/repositories-basic Use the Artisan command to quickly generate a new repository file. ```APIDOC ## Creating a Repository Generate a new repository using the following Artisan command: ```bash php artisan restify:repository PostRepository ``` This command creates the `app/Restify/PostRepository.php` file, which is then associated with your `Post` model. ``` -------------------------------- ### Apply Advanced Filter via GET Request Source: https://laravel-restify.com/docs/search/advanced-filters Send advanced filters using the `filters` query parameter in a GET request. The filter array must be JSON-encoded and then base64-encoded. ```javascript const filters = btoa(JSON.stringify([ { 'key': 'ready-posts-filter', 'value': null, } ])) const response = await axios.get(`api/restify/posts?filters=${filters}`); ``` -------------------------------- ### Writing Clear Getter Descriptions Source: https://laravel-restify.com/docs/mcp/getters Provides an example of writing a clear and specific description for a getter, explaining what data it retrieves and its scope. A good description is crucial for AI agents to understand the getter's purpose. ```php // Good: Specific, explains what data is retrieved public string $description = 'Retrieve user subscription details including plan type, billing cycle, next payment date, and usage limits. Includes historical subscription changes if requested.'; // Poor: Too vague public string $description = 'Get user subscription'; ``` -------------------------------- ### cURL Example for Email Verification Endpoint Source: https://laravel-restify.com/docs/auth/authentication Test the email verification endpoint directly using cURL. This example includes common parameters like signature and expiry, which are part of the signed URL. ```bash curl -X GET "http://restify-app.test/api/restify/verify/1/abc123hash?signature=xyz&expires=123456" \ -H "Accept: application/json" ``` -------------------------------- ### AI Agent Usage for Index Actions Source: https://laravel-restify.com/docs/mcp/actions Example AI agent inputs for index actions, demonstrating the use of a specific resource array or 'all'. ```json // Must provide resources array { "resources": ["1", "2", "3"] } // Or use "all" to apply to all resources { "resources": "all" } ``` -------------------------------- ### File Upload Automation Example Payload Source: https://laravel-restify.com/docs/mcp/fields Provides a JSON payload example for automating file uploads, typically used in workflows like n8n. It includes fields for the file path, filename, and other relevant data. ```json { "receipt_path": "", "receipt_filename": "Invoice_ABC_Company_Jan_2024", "amount": 1500.00, "date": "2024-01-15", "vendor": "ABC Company" } ``` -------------------------------- ### Creating Posts Source: https://laravel-restify.com/docs/api/repositories-basic Demonstrates how to create a new post resource using a POST request. ```APIDOC ## Creating Posts To create a new post, send a POST request to the posts endpoint with the required data in the request body. ### Request ```http POST /api/restify/posts Content-Type: application/json { "title": "My First Post", "content": "Hello World!" } ``` ### Response (Success) ```json { "data": { "id": "1", "type": "posts", "attributes": { "title": "My First Post", "content": "Hello World!", "published_at": null } } } ``` ``` -------------------------------- ### Comprehensive Action Example: Schedule Post Publication Source: https://laravel-restify.com/docs/mcp/actions An example of a comprehensive action that schedules posts for publication. It includes detailed validation rules, handles notifications, and schedules social media posts. This action is configured to only be available on the index view. ```php use Binaryk\LaravelRestify\Actions\Action; use Binaryk\LaravelRestify\Http\Requests\ActionRequest; use Illuminate\Support\Collection; class SchedulePostPublicationAction extends Action { // Clear description for AI agents public string $description = 'Schedule posts for future publication with optional notification settings. Posts will be automatically published at the specified date and time.'; // Comprehensive validation rules converted to JSON Schema public function rules(): array { return [ 'publish_at' => ['required', 'date', 'after:now'], 'timezone' => ['nullable', 'string', 'timezone'], 'notify_subscribers' => ['boolean'], 'send_social_media' => ['boolean'], 'social_platforms' => ['nullable', 'array'], 'social_platforms.*' => ['string', 'in:twitter,facebook,linkedin'], 'custom_message' => ['nullable', 'string', 'max:280'], ]; } public function handle(ActionRequest $request, Collection $posts) { $validated = $request->validate($this->rules()); foreach ($posts as $post) { $post->update([ 'scheduled_at' => $validated['publish_at'], 'timezone' => $validated['timezone'] ?? 'UTC', ]); if ($validated['notify_subscribers'] ?? false) { $post->scheduleSubscriberNotification(); } if ($validated['send_social_media'] ?? false) { $post->scheduleSocialMediaPosts( $validated['social_platforms'] ?? [], $validated['custom_message'] ?? null ); } } return ok('Posts scheduled successfully'); } } // In PostRepository public function actions(RestifyRequest $request): array { return [ SchedulePostPublicationAction::new()->onlyOnIndex(), ]; } ``` -------------------------------- ### Bulk Generate Repositories Source: https://laravel-restify.com/docs/api/repository-generation This command analyzes all models in your application and automatically generates repositories for them. It shows a preview and asks for confirmation before creation. ```bash php artisan restify:generate:repositories ``` -------------------------------- ### Update Tool Example Source: https://laravel-restify.com/docs/mcp/repositories Update an existing Post record by ID. ```APIDOC ## Update Tool Example ### Description Update an existing Post record by ID. ### Input Schema ```json { "type": "object", "properties": { "id": { "type": "string", "description": "The ID of the post to update" }, "title": { "type": "string", "description": "Title field for posts" }, "content": { "type": "string", "description": "Content field for posts" }, "status": { "type": "string", "description": "Status field for posts" }, "category": { "type": "string", "description": "Category field for posts" } }, "required": [ "id" ] } ``` ``` -------------------------------- ### API Sorting Examples Source: https://laravel-restify.com/docs/api/fields Demonstrates how API consumers can use query parameters to sort results by one or multiple fields, including descending order. ```http GET /api/restify/users?sort=name GET /api/restify/users?sort=-created_at # Descending GET /api/restify/users?sort=name,-created_at # Multiple fields ``` -------------------------------- ### Bulk Generate Repositories with Options Source: https://laravel-restify.com/docs/api/repository-generation Options for bulk repository generation include `--force` to overwrite, `--skip-preview` to bypass the preview, `--structure` to define the organization, `--only` for specific models, and `--except` to exclude models. ```bash php artisan restify:generate:repositories --structure=domains ``` ```bash php artisan restify:generate:repositories --only=User,Post ``` ```bash php artisan restify:generate:repositories --except=User,Post ``` ```bash php artisan restify:generate:repositories --force ``` ```bash php artisan restify:generate:repositories --skip-preview ``` -------------------------------- ### API Response with Meta Message Source: https://laravel-restify.com/docs/api/rest-methods Example of an API response including a meta message. ```json { "data": { "id": 1, "name": "User name", "email": "kshlerin.hertha@example.com", "email_verified_at": "2019-12-20 09:48:54", "created_at": "2019-12-20 09:48:54", "updated_at": "2020-01-10 12:01:17" }, "meta": { "message": "This is the first user" } } ``` -------------------------------- ### API Response Structure with Errors Source: https://laravel-restify.com/docs/api/rest-methods Example of an API response with an empty errors array. ```json { "errors": [] } ``` -------------------------------- ### AI Prompt: Create Repository Source: https://laravel-restify.com/docs/boost/boost Use this prompt to instruct your AI agent to create a new repository with specified fields. ```plaintext AI: Create a PostRepository with title, content, and author fields ``` -------------------------------- ### Define API Routes Source: https://laravel-restify.com/docs/api/rest-methods Define POST and GET routes for user management in `routes/api.php`. ```php Route::post('users', 'UserController@store'); Route::get('users/{id}', 'UserController@show'); ``` -------------------------------- ### Create User Controller Source: https://laravel-restify.com/docs/api/rest-methods Create a `UserController` extending `RestController` with empty `store` and `show` methods. ```php searchable(function ($request, $query, $value) { $query->where('name', 'LIKE', "%{$value}%") ->orWhere('email', 'LIKE', "%{$value}%") ->orWhere('phone', 'LIKE', "%{$value}%"); }), ``` -------------------------------- ### Advanced Policy Registration Patterns Source: https://laravel-restify.com/docs/auth/authorization Demonstrates advanced registration techniques, including defining custom gates using `Gate::define` for role-based access and dynamically registering policies for modular applications by iterating through enabled modules and their policy directories. ```php public function boot(): void { $this->registerPolicies(); // Register multiple models to one policy Gate::define('manage-content', function (User $user) { return $user->hasRole('content-manager'); }); // Dynamic policy registration for modular apps foreach (config('modules.enabled', []) as $module) { $this->registerModulePolicies($module); } } private function registerModulePolicies(string $module): void { $policiesPath = app_path("Modules/{$module}/Policies"); if (is_dir($policiesPath)) { // Auto-register policies for this module // Implementation depends on your modular structure } } ``` -------------------------------- ### API Response Structure with Data Source: https://laravel-restify.com/docs/api/rest-methods Example of a successful API response containing user data. ```json { "data": { "id": 1, "name": "User name", "email": "kshlerin.hertha@example.com", "email_verified_at": "2019-12-20 09:48:54", "created_at": "2019-12-20 09:48:54", "updated_at": "2020-01-10 12:01:17" } } ``` -------------------------------- ### Custom Show Method Source: https://laravel-restify.com/docs/api/repositories Take full control over the show method's logic by overriding it directly. This example returns the model instance directly. ```php public function show(RestifyRequest $request, $repositoryId) { return response($this->model()); } ``` -------------------------------- ### Test the API Endpoint Source: https://laravel-restify.com/ Verify your API is working by making a GET request to the users endpoint. ```bash GET /api/restify/users?perPage=10&page=1 ``` -------------------------------- ### Install Laravel Restify via Composer Source: https://laravel-restify.com/ Use this command to add the Laravel Restify package to your project. ```shell composer require binaryk/laravel-restify ``` -------------------------------- ### Bulk Delete Payload Example Source: https://laravel-restify.com/docs/api/repositories Provide an array of primary keys for the models to be deleted in a bulk operation. ```json [ 1, 10, 15 ] ``` -------------------------------- ### Retrieve User Profile with Token Source: https://laravel-restify.com/docs/auth/authentication Example of how to include the authentication token in the Authorization header for API requests. ```APIDOC ## GET /api/restify/profile ### Description Retrieves the authenticated user's profile information. ### Method GET ### Endpoint `/api/restify/profile` ### Parameters #### Headers - **Authorization** (string) - Required - The authentication token in the format `Bearer YOUR_TOKEN`. - **Accept** (string) - Required - Should be `application/json`. ### Request Example ```javascript import axios from 'axios'; const token = '1|f7D1qkALtM9GKDkjREKpwMRKTZg2ZnFqDZTSe53k'; axios.get('http://restify-app.test/api/restify/profile', { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ``` ### Request Example (cURL) ```bash curl -X GET "http://restify-app.test/api/restify/profile" \ -H "Accept: application/json" \ -H "Authorization: Bearer 1|f7D1qkALtM9GKDkjREKpwMRKTZg2ZnFqDZTSe53k" ``` ```