### PHP Example: Implementing View Transitions API Source: https://github.com/dancycodes/gale/blob/main/README.md Demonstrates how to enable the View Transitions API in PHP for smooth page transitions. It shows examples for both named views and direct HTML content updates. ```php gale()->view('page', $data, ['useViewTransition' => true]); gale()->html($html, [ 'selector' => '#content', 'useViewTransition' => true, ]); ``` -------------------------------- ### Gale Installation Commands Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/SKILL.md Provides the necessary Composer command to install the Gale package and the Artisan command to publish its assets and configuration. ```bash composer require dancycodes/gale php artisan gale:install ``` -------------------------------- ### Control Polling Start with x-interval-stop Condition Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/troubleshooting.md Explains how to manage the start and stop conditions for polling using the `x-interval-stop` directive. The condition must initially evaluate to `false` for polling to begin. ```html
``` -------------------------------- ### Basic Counter Example - Routes Source: https://github.com/dancycodes/gale/blob/main/README.md Defines a route for the counter view and a POST route to handle incrementing the count using Gale's state management. ```php Route::get('/counter', fn() => view('counter')); Route::post('/increment', function () { return gale()->state('count', request()->state('count', 0) + 1); }); ``` -------------------------------- ### PHP Example: Viewport Modifiers for Scrolling and Visibility Source: https://github.com/dancycodes/gale/blob/main/README.md Provides PHP examples of using viewport modifiers to control scrolling and visibility after DOM patches. It demonstrates scrolling to the bottom of a chat, showing the top of a form, and preserving focus scroll position. ```php // Chat: Append message and scroll to bottom gale()->append('#chat-messages', $messageHtml, ['scroll' => 'bottom']); // Form: Update and scroll into view gale()->outer('#form', $html, ['show' => 'top']); // Preserve focus position during morph gale()->outerMorph('#editor', $html, ['focusScroll' => true]); ``` -------------------------------- ### Control Component Serialization with x-sync Source: https://github.com/dancycodes/gale/blob/main/README.md Demonstrates how to use the `x-sync` directive for component-level control of serialization. It shows how to declare synced properties at the component level and provides an example of saving user data. ```html
``` -------------------------------- ### Query Alpine.gale Components by Tag Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Provides JavaScript examples for querying components based on their assigned tags or retrieving a list of all components. The `$components.getByTag()` method filters by tag, while `Alpine.gale.getAllComponents()` returns all. ```javascript const dashboardComponents = $components.getByTag('dashboard'); const all = Alpine.gale.getAllComponents(); ``` -------------------------------- ### Basic Counter Example - Blade View Source: https://github.com/dancycodes/gale/blob/main/README.md A simple Blade view demonstrating a counter with a button to increment it. It uses Alpine.js for state management and Gale's `x-sync` directive to send state updates. ```html @gale
``` -------------------------------- ### Setup - @gale Directive Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/frontend-api.md The @gale directive should be placed in the of your layout file. It automatically includes necessary scripts like Alpine.js, Morph plugin, and the Alpine Gale plugin, along with a CSRF meta tag. ```APIDOC ## Setup - @gale Directive ### Description Place in `` of your layout. Outputs CSRF meta tag + Alpine.js (v3) + Morph plugin + Alpine Gale plugin. ### Usage ```html @gale ``` **Note:** Remove any existing Alpine.js CDN or npm imports as `@gale` includes Alpine. ``` -------------------------------- ### Gale DOM Manipulation Examples (PHP) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Demonstrates various DOM manipulation methods provided by the Gale framework for updating the user interface dynamically. These include inserting elements before or after existing ones, replacing inner or outer HTML content, and utilizing View Transitions API for smooth animations. ```php // Insert as siblings ->before('#card-5', $newCardHtml) // Insert before element ->after('#card-5', $newCardHtml) // Insert after element // Inner replaces children only, outer replaces entire element ->inner('#cards-todo', $cardsHtml) // Replace children, keep container ->outer('#cards-todo', $cardsHtml) // Replace entire element // View Transitions API for smooth CSS transitions ->outer('#card-5', $html, ['useViewTransition' => true]) ->before('#card-5', $html, ['useViewTransition' => true]) ->append('#cards-todo', $html, ['useViewTransition' => true]) ``` -------------------------------- ### PHP Example: State Behavior Difference between outer and outerMorph Source: https://github.com/dancycodes/gale/blob/main/README.md Compares the state handling behavior of `outer` and `outerMorph` DOM patching modes in PHP. It demonstrates how `outer` replaces state entirely while `outerMorph` preserves client-side state. ```php // Server response includes x-data="{ count: 99 }" // outer: Client count=2 → Server sends count=99 → Result: count=99 gale()->outer('#counter', $html); // outerMorph: Client count=2 → Server sends count=99 → Result: count=2 (preserved!) gale()->outerMorph('#counter', $html); ``` -------------------------------- ### Gale Conditional Execution Logic Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md Provides examples of using Gale's conditional execution methods like `when`, `unless`, `whenGale`, `whenNotGale`, and `whenGaleNavigate` to control state and rendering based on conditions. ```php gale()->when($condition, fn($g) => $g->state('visible', true)); gale()->when($user->isAdmin(), fn($g) => $g->state('role', 'admin'), fn($g) => $g->state('role', 'user')); gale()->unless($user->isGuest(), fn($g) => $g->state('user', $user->toArray())); gale()->whenGale(fn($g) => $g->state('partial', true), fn($g) => $g->web(view('full'))); gale()->whenNotGale(fn() => view('full-page')); gale()->whenGaleNavigate('sidebar', fn($g) => $g->fragment('layout', 'sidebar', $data)); ``` -------------------------------- ### Server-Side Integration with x-name Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/frontend-api.md Example of integrating the x-name directive with a server-side route using PHP. The server can access form state values via the `Request` object's `state()` method. ```php Route::post('/api/greet', function (Request $request) { return gale()->state('response', "Hello, {$request->state('firstName')} {$request->state('lastName')}!"); }); ``` -------------------------------- ### Override Serialization Per Request with Request Options Source: https://github.com/dancycodes/gale/blob/main/README.md Illustrates how to use request options for per-request overrides of serialization behavior. This example shows how to include and exclude specific keys during an action call. ```html ``` -------------------------------- ### Basic Counter Pattern in PHP and Blade Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Demonstrates the simplest Gale pattern, illustrating the full request/response cycle. It uses PHP for routing and state management, and Blade with Alpine.js for the frontend counter interface. No external dependencies are required beyond a standard Gale setup. ```php Route::get('/counter', fn() => view('counter')); Route::post('/increment', function () { return gale()->state('count', request()->state('count', 0) + 1); }); ``` ```blade @gale
``` -------------------------------- ### HTML Example for SSE Lifecycle Events Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/frontend-api.md This HTML snippet demonstrates how to listen for SSE lifecycle events like 'gale:started' and 'gale:finished' using Vue.js-like syntax. It logs messages to the console when the SSE connection opens and closes. The button shows an example of triggering an action. ```html
``` -------------------------------- ### Provide Web Fallback for Initial Gale Page Loads in PHP Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/troubleshooting.md Demonstrates how to handle initial page loads gracefully in Gale by providing a web fallback. This prevents `LogicException` errors that can occur when Gale expects an SSE request but receives a standard web request. ```php // ❌ No fallback for initial page load return gale()->state('data', $data); // ✅ Provide web fallback return gale()->view('page', $data, web: true); // ✅ Or use web() method return gale()->state('data', $data)->web(view('page', compact('data'))); ``` -------------------------------- ### Remove Duplicate Alpine.js Installation (JavaScript/HTML) Source: https://github.com/dancycodes/gale/blob/main/README.md This section provides instructions on how to resolve the 'Detected multiple instances of Alpine running' error. It involves removing existing Alpine.js installations, whether included via CDN or npm, to prevent conflicts with the version bundled by Gale. ```html ``` ```javascript // Remove from resources/js/app.js: import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start(); ``` -------------------------------- ### File Input and Preview with Gale Source: https://github.com/dancycodes/gale/blob/main/README.md Demonstrates how to use the x-files directive for file uploads, including displaying file names, sizes, and previews. It also shows how to clear selected files using the $clearFiles magic. ```html ``` -------------------------------- ### Get Navigation Keys Source: https://github.com/dancycodes/gale/blob/main/README.md Retrieve the navigation key(s) from the request. ```APIDOC ## Get Navigation Keys ### Description Retrieve the navigation key(s) from the request. ### Method Various (uses helper functions) ### Endpoint N/A (Server-side helper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $key = request()->galeNavigateKey(); // 'sidebar' or null $keys = request()->galeNavigateKeys(); // ['sidebar', 'main'] or [] ``` ### Response #### Success Response (200) Returns the navigation key(s) as a string or an array. #### Response Example ```json { "key": "sidebar" } ``` ```json { "keys": ["sidebar", "main"] } ``` ``` -------------------------------- ### Server-Triggered Navigation with Gale (PHP) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Demonstrates various methods for triggering navigation from the server-side using the Gale library. These methods allow for controlled updates to the URL and page content, including basic navigation, merging with existing parameters, cleaning parameters, replacing history entries, and selectively including or excluding parameters. ```php // Basic server-initiated navigate gale()->navigate('/notes?search=test', 'filter'); // Merge with current URL params (preserves existing query params) gale()->navigateMerge('/notes?page=2', 'filter'); // Clean navigate (no merging, replaces all params) gale()->navigateClean('/notes?search=new', 'filter'); // Replace history entry (replaceState instead of pushState) gale()->navigateReplace('/notes?search=test', 'filter'); // Merge but exclude specific params gale()->navigateExcept('/notes?search=test', ['page'], 'filter'); // Merge but keep only specific params gale()->navigateOnly('/notes?search=test', ['search', 'category'], 'filter'); ``` -------------------------------- ### State Management Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md Methods for setting, getting, and removing state. This includes managing individual state keys or arrays of keys. ```APIDOC ## POST /gale/state ### Description Sets or updates state values. Can be used to set a single key-value pair, multiple key-value pairs, or clear specific keys. ### Method POST ### Endpoint /gale/state ### Parameters #### Query Parameters - **key** (string|array) - Required - The key or an array of keys for which to set the state. - **value** (mixed) - Optional - The value to set for the state key. If not provided, it implies clearing the state for the given key(s). - **options** (array) - Optional - Additional options for state management. ### Request Example ```json { "key": "user", "value": {"name": "John Doe", "email": "john.doe@example.com"} } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ## DELETE /gale/state ### Description Removes state keys from the application. ### Method DELETE ### Endpoint /gale/state ### Parameters #### Query Parameters - **keys** (string|array) - Required - The key or an array of keys to remove. ### Request Example ```json { "keys": ["cart", "session_id"] } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Laravel Controller State Management Source: https://github.com/dancycodes/gale/blob/main/README.md Example of how a Laravel controller can interact with Gale's state management. It retrieves state from the request and returns updated state in the response. ```php $count = request()->state('count'); return gale()->state('count', $count + 1); ``` -------------------------------- ### Implement Progressive Streaming with Gale PHP stream() Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/troubleshooting.md Illustrates the correct way to implement progressive data streaming in Gale. Using the `stream()` method ensures that events are delivered immediately rather than being batched, which is essential for real-time updates. ```php // ❌ Events batch and send together $gale = gale(); foreach ($items as $item) { $gale->state('progress', $i); } return $gale; // ✅ Use stream() for immediate delivery return gale()->stream(function ($gale) use ($items) { foreach ($items as $i => $item) { $gale->state('progress', $i); } }); ``` -------------------------------- ### Get Gale Configuration Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Retrieves the current configuration settings for Gale's confirm and navigation components. These functions do not accept any arguments and return the respective configuration objects. ```javascript Alpine.gale.getConfirmConfig(); Alpine.gale.getNavigationConfig(); ``` -------------------------------- ### gale() Helper - Get Response Builder Source: https://context7.com/dancycodes/gale/llms.txt Retrieves the singleton GaleResponse instance to build SSE events and responses. Methods can be chained to accumulate multiple actions within a single request. ```APIDOC ## gale() Helper - Get Response Builder ### Description Returns the singleton `GaleResponse` instance that accumulates SSE events throughout a request. All methods chain fluently to build complex responses. ### Method (Implicitly called via helper function) ### Endpoint (N/A - Server-side helper) ### Parameters (N/A - Helper function) ### Request Example ```php // Basic usage - chain multiple methods return gale() ->state('count', 42) ->state('updated', now()->toISOString()) ->messages(['success' => 'Saved!']); // Full controller pattern with web fallback public function index(Request $request) { $items = Item::all(); return gale()->view('items.index', compact('items'), web: true); } ``` ### Response #### Success Response (200) (Depends on chained methods, typically SSE events) #### Response Example (N/A - Server-side generation) ``` -------------------------------- ### Component Lifecycle and Event Handling Source: https://github.com/dancycodes/gale/blob/main/README.md APIs for handling component readiness, watching for component existence, and reacting to lifecycle events. ```APIDOC ## Component Lifecycle and Event Handling ### Description This section covers methods related to component lifecycle events, including waiting for components and reacting to registration/unregistration. ### Methods #### `when(name, timeout?)` - **Description**: Returns a Promise that resolves when a component with the specified name becomes available. An optional timeout can be provided. - **Parameters**: - `name` (string) - Required - The name of the component to wait for. - `timeout` (number) - Optional - The timeout in milliseconds. ### Request Example ```html
``` #### `onReady(name, callback)` - **Description**: Registers a callback function to be executed once a component is ready. - **Parameters**: - `name` (string) - Required - The name of the component. - `callback` (function) - Required - The function to execute when the component is ready. Receives the component instance as an argument. ### Request Example ```html
``` #### Lifecycle Hooks (Alpine.gale) ##### `onComponentRegistered(callback)` - **Description**: Registers a callback to be executed when a component is registered. - **Parameters**: - `callback` (function) - Required - The function to execute. Receives component name and instance. ##### `onComponentUnregistered(callback)` - **Description**: Registers a callback to be executed when a component is unregistered. - **Parameters**: - `callback` (function) - Required - The function to execute. Receives component name. ##### `onComponentStateChanged(callback)` - **Description**: Registers a callback to be executed whenever a component's state changes. - **Parameters**: - `callback` (function) - Required - The function to execute. Receives component name, property, and new value. ### Request Example ```javascript Alpine.gale.onComponentRegistered((name, component) => { console.log(`${name} registered`); }); Alpine.gale.onComponentUnregistered((name) => { console.log(`${name} unregistered`); }); Alpine.gale.onComponentStateChanged((name, property, value) => { console.log(`${name}.${property} = ${value}`); }); ``` ``` -------------------------------- ### Retrieving Gale Navigation Keys in PHP Source: https://github.com/dancycodes/gale/blob/main/README.md Get the navigation key or keys associated with a Gale request. Returns a single key or an array of keys, or null/empty array if none are found. ```php $key = request()->galeNavigateKey(); // 'sidebar' or null $keys = request()->galeNavigateKeys(); // ['sidebar', 'main'] or [] ``` -------------------------------- ### Upload Images with Progress and Preview (PHP) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Handles image uploads, validates files, stores them, and appends image cards to the gallery grid. It also updates the image count and dispatches a success toast. Dependencies include the `gale()` helper, `Image` model, and Blade views. ```php public function store(Request $request) { $request->validate(['images.*' => 'required|image|max:5120']); $gale = gale(); foreach ($request->file('images') as $file) { $image = Image::create([ 'user_id' => auth()->id(), 'filename' => $file->getClientOriginalName(), 'path' => $file->store('gallery', 'public'), ]); $html = view('gallery.partials.image-card', compact('image'))->render(); $gale->append('#gallery-grid', $html, ['show' => 'center']); } return $gale ->state('imageCount', auth()->user()->images()->count()) ->js("document.querySelector('[x-files]')?.__x_files?.clear()") ->dispatch('toast', ['type' => 'success', 'message' => 'Uploaded!']); } ``` -------------------------------- ### Gale Route Discovery with Attributes Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md Demonstrates how to use PHP attributes for route discovery in Gale. This includes defining routes, prefixes, parameter constraints, and excluding methods/classes from discovery. ```php use Dancycodes\Gale\Routing\Attributes\{Route, Prefix, Where, DoNotDiscover, WithTrashed}; #[Prefix('/admin')] #[Route(middleware: 'auth')] class UserController extends Controller { #[Route('GET', '/users', name: 'admin.users.index')] public function index() { } #[Route('GET', '/users/{id}', name: 'admin.users.show')] #[Where('id', Where::NUMERIC)] #[WithTrashed] public function show($id) { } #[Route(['GET', 'POST'], '/users/search')] public function search() { } #[DoNotDiscover] public function internalMethod() { } } ``` -------------------------------- ### Tag and Query Alpine.gale Components Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Demonstrates how to tag components using the `data-tags` attribute and how to query components by these tags or retrieve all registered components. This utilizes Alpine.gale's `$components` proxy. ```html
``` -------------------------------- ### Register Components with x-component Directive in HTML Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/troubleshooting.md Demonstrates how to register a component for state management using the `x-component` directive. This is necessary for `componentState()` to correctly update the component's state. ```html
``` -------------------------------- ### Server-Side Validation and Message Generation Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/frontend-api.md Provides examples of server-side validation using PHP and how to send structured messages with type prefixes that automatically map to CSS classes. This ensures consistent feedback to the user. ```php $request->validateState([ 'items' => 'required|array|min:1', 'items.*.name' => 'required|string|min:2', ]); gale()->messages([ 'email' => '[ERROR] Invalid email', 'saved' => '[SUCCESS] Changes saved', 'note' => '[WARNING] Session expiring', 'info' => '[INFO] New features available', ]); ``` -------------------------------- ### Viewport Scroll Options (PHP) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Demonstrates various options for controlling the viewport scroll position when appending or prepending content. Options include scrolling to the bottom, top, center of a new element, or maintaining the current scroll position. Used with `append` and `prepend` methods. ```php ->append('#list', $html, ['scroll' => 'bottom']) // Scroll container to bottom ->prepend('#list', $html, ['scroll' => 'top']) // Scroll container to top ->append('#list', $html, ['show' => 'center']) // Scroll new element into viewport center ->append('#list', $html, ['focusScroll' => true]) // Maintain current scroll position ``` -------------------------------- ### Gale Helper Function Initialization Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md The `gale()` helper function returns a singleton `GaleResponse` instance. This instance is used to chain API methods for accumulating Server-Sent Events (SSE) throughout a request, which are then streamed to the client. ```php return gale() ->state('count', 42) ->state('updated', now()->toISOString()) ->messages(['success' => 'Saved!']); ``` -------------------------------- ### Alpine.js Context Requirement for Gale Features Source: https://github.com/dancycodes/gale/blob/main/README.md Demonstrates how Gale features require an Alpine.js context to function correctly. Code examples show valid usage within x-data or x-init, and invalid usage outside an Alpine context. ```html
Loading...
``` -------------------------------- ### Redirect Back or to Route (PHP) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md Provides options to redirect back to the previous page or to a specific named route with parameters. If going back fails, it falls back to a default route. ```php return gale()->redirect('/')->back('/fallback'); return gale()->redirect('/')->route('dashboard'); return gale()->redirect('/')->backOr('home'); ``` -------------------------------- ### Backend Validation with Laravel and Gale Source: https://github.com/dancycodes/gale/blob/main/README.md Provides a PHP example using Laravel's `validateState` method to validate an array of items. It demonstrates how to define validation rules, custom error messages, and return success messages via Gale. ```php Route::post('/validate-items', function (Request $request) { $validated = $request->validateState([ 'items' => 'required|array|min:1', 'items.*.name' => 'required|string|min:2', 'items.*.quantity' => 'required|integer|min:1', ], [ 'items.*.name.required' => 'Item name is required', 'items.*.name.min' => 'Item name must be at least 2 characters', 'items.*.quantity.min' => 'Quantity must be at least 1', ]); return gale()->messages(['_success' => 'All items validated!']); }); ``` -------------------------------- ### Alpine.js x-sync and Request Options with HTML Source: https://github.com/dancycodes/gale/blob/main/README.md Demonstrates how the 'include' and 'exclude' options on HTTP magics work with 'x-sync' in Alpine.js. It shows how state is included or excluded in requests based on these configurations. ```html
``` -------------------------------- ### Frontend Navigation Patterns with x-navigate Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/SKILL.md Handles Single Page Application (SPA) navigation using the x-navigate directive. It allows for intercepting links, navigating with specific keys, and skipping navigation for external links. ```html {{-- Frontend: x-navigate on container delegates to all child links --}}
Page 1 {{-- Intercepted by Gale --}} Page 2 {{-- With navigate key --}} External {{-- Skipped --}}
{{-- Programmatic: $navigate magic --}} ``` -------------------------------- ### Gale CSRF Configuration with JavaScript Source: https://github.com/dancycodes/gale/blob/main/README.md Shows how to configure CSRF protection in Gale using the '@gale' directive and the '$action' magic. It includes examples for configuring header names, meta names, and cookie names, as well as retrieving the current configuration. ```javascript Alpine.gale.configureCsrf({ headerName: "X-CSRF-TOKEN", metaName: "csrf-token", cookieName: "XSRF-TOKEN", }); // Get current config const config = Alpine.gale.getCsrfConfig(); ``` -------------------------------- ### Gale Route Discovery Configuration Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/backend-api.md Shows how to enable and configure route discovery in Gale by modifying the `config/gale.php` file. This includes specifying directories for controllers and views, and defining route transformers. ```php // config/gale.php 'route_discovery' => [ 'enabled' => true, 'discover_controllers_in_directory' => [app_path('Http/Controllers')], 'discover_views_in_directory' => ['docs' => resource_path('views/docs')], 'pending_route_transformers' => [ ...Dancycodes\Gale\Routing\Config::defaultRouteTransformers(), ], ], ``` -------------------------------- ### Rate Limiting for API Endpoints in PHP Source: https://github.com/dancycodes/gale/blob/main/SECURITY.md Demonstrates how to implement rate limiting for API endpoints using Laravel's middleware. This example applies a throttle of 60 requests per minute to a POST route, helping to prevent abuse and denial-of-service attacks. ```php Route::post('/search', [SearchController::class, 'search']) ->middleware('throttle:60,1'); ``` -------------------------------- ### Authorization Checks Example in PHP Source: https://github.com/dancycodes/gale/blob/main/SECURITY.md Illustrates how to implement authorization checks before performing sensitive operations, such as deleting a post. It verifies if the authenticated user has the necessary permissions using Laravel's Gates or Policies. This prevents unauthorized users from modifying or deleting data. ```php public function delete($id) { $post = Post::findOrFail($id); if (!auth()->user()->can('delete', $post)) { abort(403); } $post->delete(); return gale()->state(['deleted' => true]); } ``` -------------------------------- ### Publish Gale Configuration Source: https://github.com/dancycodes/gale/blob/main/README.md This command publishes the Gale configuration file to your Laravel project. This allows you to customize Gale's behavior according to your project's needs. ```bash php artisan vendor:publish --tag=gale-config ``` -------------------------------- ### gale() Helper - Get Response Builder in PHP Source: https://context7.com/dancycodes/gale/llms.txt The gale() helper returns the singleton GaleResponse instance to build SSE events. It supports chaining methods for state updates, messages, and view rendering. The 'web: true' option provides a fallback for non-Gale requests. ```php return gale() ->state('count', 42) ->state('updated', now()->toISOString()) ->messages(['success' => 'Saved!']); ``` ```php public function index(Request $request) { $items = Item::all(); return gale()->view('items.index', compact('items'), web: true); } ``` -------------------------------- ### Server-Side Validation Example in PHP Source: https://github.com/dancycodes/gale/blob/main/SECURITY.md Demonstrates how to perform server-side validation using Laravel's request validation. It ensures that incoming data meets specific criteria like required fields, email format, and allowed values for roles. This is crucial for preventing invalid data from being processed. ```php public function update(Request $request) { $validated = $request->validate([ 'email' => 'required|email|unique:users', 'role' => 'required|in:user,admin' ]); // Use validated data... } ``` -------------------------------- ### File Upload Zone with Live Preview (Blade) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Provides a user interface for selecting multiple image files, displaying previews, file names, and sizes. It includes an upload progress indicator and an upload button that triggers the action. Relies on Alpine.js directives like `x-data`, `x-files`, and `$action`. ```blade
``` -------------------------------- ### CSRF Auto-Injection with $action Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/frontend-api.md Gale automatically injects CSRF tokens for POST, PUT, PATCH, and DELETE requests made via `$action()`. This is read from the `` tag, which is output by the `@gale` directive. GET requests do not require CSRF. ```html ``` -------------------------------- ### Run Gale Package Tests (Bash) Source: https://github.com/dancycodes/gale/blob/main/README.md This bash script outlines the commands to execute tests for the Dancycodes Gale package. It includes running PHPUnit for unit tests, PHPStan for static analysis, and Pint for code style checks. ```bash cd packages/dancycodes/gale vendor/bin/phpunit vendor/bin/phpstan analyse vendor/bin/pint ``` -------------------------------- ### Table Bulk Actions and Form Updates (Blade) Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/patterns.md Provides buttons for performing bulk delete actions, exporting data, and saving record changes using different HTTP methods (PUT for full replacement, PATCH for partial updates). It utilizes Alpine.js directives for confirmation and data inclusion. Includes examples for cross-component data sharing. ```blade {{-- Export with cross-component data --}}
{{-- PUT = full replacement (all fields required) --}} {{-- PATCH = partial update (only changed fields) --}} ``` -------------------------------- ### Fix Navigation Not Working with Backend Handling in PHP Source: https://github.com/dancycodes/gale/blob/main/ai-skill/gale/references/troubleshooting.md Ensures the backend correctly handles SPA navigation requests by checking if the request is a Gale navigation request using `isGaleNavigate()`. If it is, return the fragment; otherwise, return the full view. ```php // ❌ Returns full page for navigate requests too public function index() { return view('page'); } // ✅ Check for navigate and return fragments public function index(Request $request) { $data = $this->getData(); if ($request->isGaleNavigate('content')) { return gale()->fragment('page', 'content', $data); } return gale()->view('page', $data, web: true); } ``` -------------------------------- ### View and Fragment Rendering Source: https://github.com/dancycodes/gale/blob/main/README.md Methods for rendering views and fragments, allowing for dynamic content generation. ```APIDOC ## View and Fragment Rendering ### Description Methods for rendering views and fragments. ### Methods #### `view(string $view, array $data = [], array $options = [], bool $web = false)` Render view. #### `fragment(string $view, string $fragment, array $data = [], array $options = [])` Render fragment. #### `fragments(array $fragments)` Render multiple fragments. ```