### Start Hybridly Development Server
Source: https://hybridly.dev/guide/installation
Launches the Hybridly development server using npm and provides the command to open the application in a browser. This command builds your application and starts a local development server.
```shell
npm run dev
open https://hybridly-app.test
```
--------------------------------
### Initialize Git Repository (Bash)
Source: https://hybridly.dev/guide/installation
Initializes a Git repository in the project's root directory and stages all files for the first commit. This is a standard practice for version control when starting a new project.
```bash
git init
git add .
git commit -m "chore: initialize project"
```
--------------------------------
### Install Hybridly Preset (Bash)
Source: https://hybridly.dev/guide/installation
Installs Hybridly using a preset for a fresh Laravel project. This command simplifies the setup of Hybridly, Tailwind CSS, and Pest. Additional flags can customize the installation, such as `--i18n` for vue-i18n.
```bash
npx @preset/cli apply hybridly/preset
```
```bash
pnpm dlx @preset/cli apply hybridly/preset
```
```bash
bunx @preset/cli apply hybridly/preset
```
```bash
yarn dlx @preset/cli apply hybridly/preset
```
--------------------------------
### Initialize Hybridly Application
Source: https://hybridly.dev/guide/installation
Initializes the Hybridly application within your main entry point (`resources/application/main.ts`). This setup involves configuring Vue and Hybridly. The `enhanceVue` function can be used for further Vue customizations.
```typescript
import { createApp } from 'vue'
import { initializeHybridly } from 'virtual:hybridly/config'
initializeHybridly({
enhanceVue: (vue) => {}
})
```
--------------------------------
### Create Laravel Project and Install Dependencies (Bash)
Source: https://hybridly.dev/guide/installation
Creates a new Laravel project using Composer and then installs Node.js dependencies using pnpm. This is a foundational step for a manual Hybridly installation, setting up the basic Laravel structure and its frontend dependencies.
```bash
composer create-project laravel/laravel hybridly-app
cd hybridly-app
pnpm install
```
--------------------------------
### Install Hybridly with Preset (Bash)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Installs Hybridly using the automated preset via npx. Supports additional options to customize the installation, such as disabling i18n or Pest testing.
```bash
npx @preset/cli apply hybridly/preset
# With additional options
npx @preset/cli apply hybridly/preset --i18n --no-pest --no-strict --no-ide
```
--------------------------------
### Install Client Dependencies (Bash)
Source: https://hybridly.dev/guide/installation
Installs the Hybridly, Vue, and Axios npm packages as development dependencies. This command is used for the client-side setup of Hybridly. The command varies slightly depending on the package manager used (npm, pnpm, bun, yarn).
```bash
ni hybridly vue axios -D
```
```bash
pnpm i hybridly vue axios -D
```
```bash
bun i hybridly vue axios -D
```
```bash
npm i hybridly vue axios -D
```
```bash
yarn add hybridly vue axios -D
```
--------------------------------
### Install Hybridly, Vue, and Axios Packages
Source: https://hybridly.dev/guide/installation
Installs the necessary packages for Hybridly, Vue, and Axios as development dependencies using npm. Ensure you have Node.js and npm installed.
```bash
npm install hybridly vue axios -D
```
--------------------------------
### Manual Backend Installation for Hybridly (Bash)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Installs the Hybridly Laravel package and runs the necessary artisan command. This command sets up the HandleHybridRequests middleware in your application.
```bash
# Install Laravel package
composer require hybridly/laravel
php artisan hybridly:install
```
--------------------------------
### Initialize Hybridly (TypeScript)
Source: https://hybridly.dev/guide/installation
Initializes Hybridly within the client-side application by calling the `initializeHybridly` function. This setup typically occurs in a `main.ts` file and is the entry point for Hybridly's client-side configuration. It also mentions the use of `enhanceVue` for further customization.
```typescript
import { initializeHybridly } from 'virtual:hybridly/config'
initializeHybridly()
```
--------------------------------
### Install Laravel Package (Bash)
Source: https://hybridly.dev/guide/installation
Installs the Hybridly Laravel package using Composer and runs the hybridly:install Artisan command. This command sets up the necessary middleware for Hybridly to function within the Laravel application.
```bash
composer require hybridly/laravel
php artisan hybridly:install
```
--------------------------------
### PHP to TypeScript Transformation Setup (Bash & PHP)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Details the installation and configuration steps for setting up PHP to TypeScript transformation using `spatie/laravel-data` and `spatie/laravel-typescript-transformer`. This enables automatic generation of TypeScript types from PHP data objects.
```bash
# Install required packages
composer require spatie/laravel-data
composer require spatie/laravel-typescript-transformer
php artisan vendor:publish --tag=typescript-transformer-config
```
```php
// config/typescript-transformer.php
'collectors' => [
Spatie\TypeScriptTransformer\Collectors\DefaultCollector::class,
Spatie\TypeScriptTransformer\Collectors\EnumCollector::class,
Hybridly\Support\TypeScriptTransformer\DataResourceTypeScriptCollector::class,
Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptCollector::class,
],
'transformers' => [
Spatie\LaravelTypeScriptTransformer\Transformers\SpatieStateTransformer::class,
Spatie\TypeScriptTransformer\Transformers\SpatieEnumTransformer::class,
Spatie\TypeScriptTransformer\Transformers\DtoTransformer::class,
Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptTransformer::class,
]
```
--------------------------------
### Basic View Component Creation (Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Shows how to create a basic Vue view component using the `
```
--------------------------------
### Define a Route to Load a View
Source: https://hybridly.dev/guide/installation
Creates a web route in `routes/web.php` that maps the root URL ('/') to the `index` view component using the `hybridly` function. This makes your view accessible via a browser.
```php
Route::get('/', function () {
return hybridly('index');
});
```
--------------------------------
### TypeScript Configuration (JSON)
Source: https://hybridly.dev/guide/installation
Sets up the TypeScript configuration file (`tsconfig.json`) for a Hybridly project. It extends the base Hybridly TypeScript configuration, ensuring proper type checking and IntelliSense for Hybridly-specific features.
```json
{
"extends": "./.hybridly/tsconfig.json"
}
```
--------------------------------
### Create a Vue View Component
Source: https://hybridly.dev/guide/installation
Defines a basic Vue component (`index.vue`) that will serve as a view in your Hybridly application. This is a standard Vue component structure.
```vue
Hello Hybridly
```
--------------------------------
### File Downloads with PHP
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Provides examples of handling file downloads in PHP using Laravel's response capabilities. It covers downloading an invoice using its file path and downloading a file from storage. Dependencies include Illuminate\Support\Facades\Storage and response()->download.
```php
use Illuminate\Support\Facades\Storage;
public function downloadInvoice(Invoice $invoice)
{
return response()->download(
$invoice->file_path,
'invoice.pdf'
);
}
public function downloadReport()
{
return Storage::download('reports/monthly.pdf');
}
```
--------------------------------
### Hybridly Controller Example (PHP)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
A Laravel controller demonstrating how to return Hybridly views with data. It shows fetching a user, transforming it into a UserData object, and passing it to the 'users.show' view. It also includes an update method with request validation.
```php
// app/Http/Controllers/UserProfileController.php
use AppDataUserData;
use AppModelsUser;
use function Hybridly\view;
final class UserProfileController
{
public function show(User $user)
{
return view('users.show', [
'user' => UserData::from($user)
]);
}
public function update(User $user, UpdateUserRequest $request)
{
$user->update($request->validated());
return back()->with('success', 'Changes saved.');
}
}
```
--------------------------------
### Root Blade Template (Blade)
Source: https://hybridly.dev/guide/installation
Defines the root Blade template for a Hybridly application. This file includes essential HTML structure, meta tags, and utilizes Vite for asset compilation. The `@hybridly` directive renders the Hybridly application within the body.
```blade
@vite
@hybridly
```
--------------------------------
### Configure Vite Plugin (TypeScript)
Source: https://hybridly.dev/guide/installation
Configures Vite by renaming the `vite.config.js` file to `vite.config.ts` and registering the Hybridly Vite plugin. This ensures that Hybridly assets and functionalities are correctly processed by Vite during development and build.
```typescript
import { defineConfig } from 'vite'
import hybridly from 'hybridly/vite'
export default defineConfig({
plugins: [
hybridly(),
],
})
```
--------------------------------
### Test Hybrid Responses with Hybridly
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
This snippet showcases how to test Hybridly responses in feature tests. It includes examples of asserting successful page loads, checking for specific Hybrid views and properties, and verifying the presence or absence of shared data like user information. It also demonstrates testing form submissions and validation errors.
```php
// tests/Feature/UsersTest.php
use App\Models\User;
test('users can see the index page', function () {
get('/')
->assertOk()
->assertHybrid()
->assertHybridView('index')
->assertMissingHybridProperty('security.user');
});
test('authenticated users see their profile', function () {
$user = User::factory()->create();
actingAs($user)
->get('/profile')
->assertOk()
->assertHybrid()
->assertHybridView('profile.show')
->assertHybridProperty('user.id', $user->id)
->assertHybridProperty('user.name', $user->name);
});
test('users can update their profile', function () {
$user = User::factory()->create();
actingAs($user)
->put('/profile', [
'name' => 'New Name',
'email' => 'new@example.com',
])
->assertRedirect()
->assertSessionHas('success');
expect($user->fresh())
->name->toBe('New Name')
->email->toBe('new@example.com');
});
test('validation errors are returned', function () {
$user = User::factory()->create();
actingAs($user)
->put('/profile', [
'name' => '',
'email' => 'invalid-email',
])
->assertHybridProperty('errors.name')
->assertHybridProperty('errors.email');
});
```
--------------------------------
### Root Blade Template with Vite Assets (Blade)
Source: https://hybridly.dev/guide/installation
An alternative definition for the root Blade template, explicitly including CSS and TypeScript entry points in the Vite compilation. This ensures that both the application's styles and the Hybridly client-side logic are loaded correctly.
```blade
@vite(['resources/css/app.css', 'resources/application/main.ts'])
@hybridly
```
--------------------------------
### Defining Hybridly Routes in Laravel (PHP)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Defines web routes in Laravel that will be handled by Hybridly. It demonstrates defining a GET route for user profiles and a PUT route for updating user information.
```php
// routes/web.php
use AppDataUserData;
use AppModelsUser;
use function Hybridly\view;
Route::get('/users/{user}', [UserProfileController::class, 'show'])
->name('users.show');
Route::put('/users/{user}/update', [UserProfileController::class, 'update'])
->name('users.update');
```
--------------------------------
### Link Component with Preloading (Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates the use of Hybridly's router-link component for basic navigation and preloading functionality. Preloading can be triggered on hover or on mount to improve performance.
```vue
HomeDashboardSettings
```
--------------------------------
### Backend Setup for Data Refining in PHP
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
This PHP code sets up backend refining for a 'Chirp' model using Hybridly's `Refine` facade. It defines default sorting ('created_at' descending), available sorts ('likes_count'), and various filter types including text ('body'), select ('category'), trashed items, and boolean ('is_featured'). This configuration is then passed to the frontend.
```php
// app/Http/Controllers/ChirpController.php
use AppModelsChirp;
use Hybridly\Refining\{Sorts, Filters};
use Hybridly\Refining\Refine;
public function index()
{
$this->authorize('viewAny', Chirp::class);
$chirps = Refine::model(Chirp::class)->with([
Sorts\Sort::make('created_at', alias: 'date')->default('desc'),
Sorts\Sort::make('likes_count', alias: 'likes'),
Filters\Filter::make('body')->loose(),
Filters\SelectFilter::make('category', options: [
'tech', 'news', 'sports'
]),
Filters\TrashedFilter::make(),
Filters\BooleanFilter::make('is_featured'),
]);
return hybridly('chirps.index', [
'chirps' => ChirpData::collection($chirps->paginate()),
'refinements' => $chirps->refinements(),
]);
}
```
--------------------------------
### Hybridly Plugin Lifecycle Hooks
Source: https://hybridly.dev/guide/plugins
Defines the available lifecycle hooks for Hybridly plugins, including `initialized`, `ready`, `backForward`, `navigating`, `navigated`, and `mounted`. These hooks allow for precise control over Hybridly's navigation and initialization process.
```typescript
export interface Hooks extends RequestHooks {
/**
* Called when Hybridly's context is initialized.
*/
initialized: (context: InternalRouterContext) => MaybePromise
/**
* Called after Hybridly's initial load.
*/
ready: (context: InternalRouterContext) => MaybePromise
/**
* Called when a back-forward navigation occurs.
*/
backForward: (state: any, context: InternalRouterContext) => MaybePromise
/**
* Called when a component navigation is being made.
*/
navigating: (options: InternalNavigationOptions, context: InternalRouterContext) => MaybePromise
/**
* Called when a component has been navigated to.
*/
navigated: (options: InternalNavigationOptions, context: InternalRouterContext) => MaybePromise
/**
* Called when a component has been navigated to and was mounted by the adapter.
*/
mounted: (options: InternalNavigationOptions & MountedHookOptions, context: InternalRouterContext) => MaybePromise
}
```
--------------------------------
### Form Composable with Validation (Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Provides an example of using Hybridly's `useForm` composable to create reactive forms. It covers defining form fields, submission methods, URL, data transformation, lifecycle hooks, and displaying validation errors.
```vue
```
--------------------------------
### External Redirects with PHP Hybridly
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates how to perform external redirects using Hybridly in PHP. It shows how to redirect to an external URL and how to open a link in a new tab. Dependencies include `to_external_url` from Hybridly and `Target` from Hybridly\Support.
```php
use function Hybridly\to_external_url;
use Hybridly\Support\Target;
// Redirect to external URL
return to_external_url('https://google.com');
// Open in new tab
return to_external_url('https://google.com', target: Target::NEW_TAB);
```
--------------------------------
### Vue Single-File Component for User Profile Form
Source: https://hybridly.dev/guide/index
An example of a Vue single-file component used with Hybridly for rendering a user profile page. It utilizes Hybridly's `route` utility and `useForm` hook for form handling and submission, along with a persistent layout.
```vue
```
--------------------------------
### Install laravel-data for Hybridly
Source: https://hybridly.dev/guide/typescript
Installs the `spatie/laravel-data` package, which provides a way to create rich data objects and is essential for generating TypeScript interfaces when building hybrid applications.
```bash
composer require spatie/laravel-data
```
--------------------------------
### Hybridly Initialization in Vue (TypeScript)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Initializes Hybridly in your Vue application's main entry point. It allows for custom Vue enhancements, such as registering plugins or global components.
```typescript
import { initializeHybridly } from 'virtual:hybridly/config'
initializeHybridly({
enhanceVue: (vue) => {
// Register plugins, components, directives here
}
})
```
--------------------------------
### Simulating Deferred Property Loading in TypeScript
Source: https://hybridly.dev/guide/partial-reloads
Provides a TypeScript example that mimics the behavior of deferred properties by manually triggering a partial reload for a specific property within the `onMounted` hook. This approach is functionally equivalent to using `deferred()` in PHP.
```typescript
import { defineProps, onMounted } from 'vue';
import router from '@/router';
defineProps<{
slowProperty?: Data.ThirdPartyDataType
}>()
onMounted(() => {
router.reload({ only: ['slowProperty'] })
})
```
--------------------------------
### Install @unhead/vue for Hybridly
Source: https://hybridly.dev/guide/title-and-meta
Install the @unhead/vue package as a development dependency using npm. This package is essential for managing head tags in your Hybridly application.
```bash
npm i -D @unhead/vue
```
--------------------------------
### Registering a Plugin in Hybridly
Source: https://hybridly.dev/guide/plugins
Demonstrates how to register a custom plugin globally within your Hybridly application using the `initializeHybridly` function. Ensure the plugin is correctly imported and instantiated.
```typescript
import { MyPlugin } from 'hybridly-plugin-something'
initializeHybridly({
plugins: [
MyPlugin()
],
})
```
--------------------------------
### Creating Data Resources with PHP Authorization
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Shows how to define authorization capabilities for data resources in PHP using Hybridly's `DataResource`. It includes defining static `$authorizations` and implementing policy methods in a separate policy class. Dependencies include `DataResource` from Hybridly\Support\Data and Carbon.
```php
// app/Data/ChirpData.php
author->is($user);
}
public function like(User $user, Chirp $chirp): bool
{
return !$user->hasLiked($chirp);
}
public function unlike(User $user, Chirp $chirp): bool
{
return $user->hasLiked($chirp);
}
}
```
--------------------------------
### Programmatic Navigation with Hybridly Router (TypeScript)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Shows how to use the `router` object provided by Hybridly for programmatic navigation within a Vue application. It covers various HTTP methods, external navigation, page reloads, and preloading routes.
```typescript
// In any .vue or .ts file
import { router } from 'hybridly'
// GET request
router.get('/users')
// POST request with data
router.post('/users', {
data: { name: 'John', email: 'john@example.com' }
})
// DELETE request
router.delete('/users/1')
// External navigation
router.external('https://example.com')
// Reload current page
router.reload()
// Reload with options
router.reload({ only: ['users'] })
// Preload a route
router.preload('/dashboard')
```
--------------------------------
### Update Vite Plugin Configuration (TypeScript)
Source: https://hybridly.dev/guide/upgrade/v0
Demonstrates the removal of the `php` option from the Hybridly Vite plugin configuration. The PHP executable path should now be managed via the `PHP_EXECUTABLE_PATH` environment variable.
```typescript
ts```
export default defineConfig({
plugins: [
hybridly({
php: 'custom/path/to/php'
}),
],
})
```
```
--------------------------------
### Typed Data Objects (PHP & Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates how to create typed data objects in PHP using `spatie/laravel-data` and how these types are automatically recognized and utilized in Vue components for full TypeScript autocompletion.
```php
// app/Data/UserData.php
```
--------------------------------
### Install and Configure laravel-typescript-transformer
Source: https://hybridly.dev/guide/typescript
Installs the `spatie/laravel-typescript-transformer` package and publishes its configuration file. This allows for the generation of TypeScript interfaces from PHP data objects and enums.
```bash
composer require spatie/laravel-typescript-transformer
php artisan vendor:publish --tag=typescript-transformer-config
```
--------------------------------
### Developing a Hybridly Plugin
Source: https://hybridly.dev/guide/plugins
Shows the basic structure of a Hybridly plugin using the `definePlugin` helper function. Plugins require a `name` property and can hook into various lifecycle events, such as `initialized`.
```typescript
import { definePlugin } from 'hybridly'
export default function MyPlugin(options?: MyPluginOptions) {
return definePlugin({
name: 'hybridly:my-plugin',
initialized(context) {
console.log('Hybridly has been initialized')
},
// Other lifecycle hooks
})
}
export interface MyPluginOptions {
// ...
}
```
--------------------------------
### Hybridly Programmatic Navigation API
Source: https://hybridly.dev/guide/navigation
This section outlines the Hybridly router API for programmatically initiating navigations. It includes methods for GET, POST, DELETE requests, external links, preloading, reloading, and general navigation. These functions allow for dynamic routing within the application.
```typescript
router.get(url, options)
router.post(url, options)
router.delete(url, options)
router.external(url, options)
router.preload(url, options)
router.reload(options)
router.navigate(options)
```
--------------------------------
### Initialize Hybridly with Custom Progress Indicator Options
Source: https://hybridly.dev/guide/progress-indicator
This snippet demonstrates how to initialize Hybridly with custom configuration for its built-in progress indicator. You can adjust the indicator's color, delay before showing, whether to include default CSS, and if a spinner should be displayed. These options allow fine-tuning the visual feedback provided to the user during background requests.
```typescript
initializeHybridly({
progress: {
color: '#fca5a5',
delay: 250,
includeCSS: true,
spinner: false,
}
})
```
--------------------------------
### Hybridly Form Request Lifecycle Hooks
Source: https://hybridly.dev/guide/forms
This TypeScript snippet illustrates how to use the `hooks` property within `useForm` to execute custom logic at different stages of a request lifecycle. It includes examples for `start`, `fail`, and `after` hooks, allowing developers to manage actions before, during, and after a form submission.
```ts
useForm({
fields: {
body: '',
},
hooks: {
start: () => console.log('The request has started.'),
fail: () => console.log('The request has failed.'),
after: () => console.log('The request has finished.'),
}
})
```
--------------------------------
### Returning Hybrid Responses with PHP
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Illustrates how to return hybrid responses using the `view` function from Hybridly in PHP. This includes displaying a list of chirps with pagination and handling the creation of new chirps. Dependencies include App\Data\ChirpData, App\Models\Chirp, and the `view` function from Hybridly.
```php
use App\Data\ChirpData;
use App\Models\Chirp;
use function Hybridly\view;
class ChirpController extends Controller
{
public function index()
{
$this->authorize('viewAny', Chirp::class);
$chirps = Chirp::query()
->forHomePage()
->paginate();
return view('chirps.index', [
'chirps' => ChirpData::collection($chirps),
]);
}
public function store(CreateChirpRequest $request)
{
$chirp = Chirp::create($request->validated());
return to_route('chirps.index')
->with('success', 'Chirp created successfully!');
}
}
```
--------------------------------
### Laravel Policy Example - PHP
Source: https://hybridly.dev/guide/authorization
Provides an example of a Laravel Policy class (`ChirpPolicy`) in PHP, demonstrating how to define authorization methods for different actions (comment, delete, like, unlike) based on the authenticated user and the given resource. It uses `HandlesAuthorization` trait.
```php
use App\Models\Chirp;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class ChirpPolicy
{
use HandlesAuthorization;
public function comment(User $user):
public function delete(User $user, Chirp $chirp):
public function like(User $user, Chirp $chirp):
public function unlike(User $user, Chirp $chirp):
}
```
--------------------------------
### Define a Route for a Hybridly View (PHP)
Source: https://hybridly.dev/guide/views-and-layouts
This PHP snippet defines a GET route for '/users/{user}' that is handled by the `ShowUserController`. It names the route 'users.show', which is commonly used to reference the view in the `hybridly()` function.
```php
Route::get('/users/{user}', ShowUserController::class)->name('users.show');
```
--------------------------------
### Backend Partial Reloads and Deferred Loading with PHP
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Illustrates how to implement partial reloads and deferred loading on the backend using Hybridly in PHP. It shows how to define properties that are only evaluated when requested (`partial`) or after the initial page load (`deferred`). Dependencies include `partial` and `deferred` from Hybridly.
```php
use function Hybridly\partial;
use function Hybridly\deferred;
public function index()
{
return hybridly('dashboard', [
'users' => UserData::collection(User::paginate()),
// Only evaluated when specifically requested
'filters' => partial(fn () => $this->getAvailableFilters()),
// Evaluated after initial page load
'analytics' => deferred(fn () => $this->fetchAnalytics()),
]);
}
```
--------------------------------
### Route Definitions for User Profiles in PHP
Source: https://hybridly.dev/guide/index
Defines routes for fetching and updating user profiles within a Laravel application. These routes are designed to work with controllers that utilize Hybridly for rendering views.
```php
Route::get('/users/{user}', [UserProfileController::class, 'show'])
->name('users.show');
Route::put('/users/{user}/update', [UserProfileController::class, 'update'])
->name('users.update');
```
--------------------------------
### Share Query Results and Refinements with View
Source: https://hybridly.dev/guide/refining
Provides an example of a controller method that executes a refined query, obtains both the paginated results and the refinement definitions, and shares them as properties to the Hybridly view. This enables the view to render dynamic UI elements for refinement.
```php
public function index()
{
$this->authorize('viewAny', Chirp::class);
$chirps = Refine::model(Chirp::class)->with([
Sorts\Sort::make('created_at', alias: 'date'),
Filters\TrashedFilter::make(),
])->forHomePage();
return hybridly('chirps.index', [
'chirps' => ChirpData::collection($chirps->paginate()),
'refinements' => $chirps->refinements(),
]);
}
```
--------------------------------
### Uninstall Inertia and Ziggy npm Packages
Source: https://hybridly.dev/guide/migrating-from-inertia
This command uninstalls various Inertia.js and Ziggy.js related npm packages. It's crucial to remove these before installing Hybridly equivalents.
```bash
npm uninstall \
@inertiajs/progress @inertiajs/inertia @inertiajs/inertia-vue3 \
ziggy-js @types/ziggy-js
```
--------------------------------
### Replace useContext with getRouterContext (TypeScript)
Source: https://hybridly.dev/guide/upgrade/v0
Illustrates the replacement of the `useContext` function with `getRouterContext` for accessing router context. This change requires updating existing calls to retrieve URL information.
```typescript
ts```
const url = useContext().value?.url
const url = getRouterContext()?.url
```
```
--------------------------------
### Update defineLayout and defineLayoutProperties to defineOptions (TypeScript)
Source: https://hybridly.dev/guide/upgrade/v0
Replaces the deprecated `defineLayout` and `defineLayoutProperties` functions with the `defineOptions` macro provided by Vue 3.3+. This change streamlines layout definition and property management.
```typescript
ts```
defineLayout(main)
defineLayoutProperties({
fullscreen: false,
})
```
```
```typescript
ts```
defineOptions({
layout: main,
properties: {
fullscreen: false,
},
})
```
```
--------------------------------
### Backend Validation Handling with PHP Form Requests
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates how to create and use Form Requests in PHP for backend validation. It includes defining validation rules in a Form Request class and applying it to a controller method for handling login requests. Dependencies include Illuminate\Foundation\Http\FormRequest and Illuminate\Support\Facades\Auth.
```php
// app/Http/Requests/LoginRequest.php
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
public function rules(): array
{
return [
'email' => ['required', 'email'],
'password' => ['required', 'string', 'min:8'],
'remember' => ['string'],
];
}
}
```
```php
// Controller
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
public function login(LoginRequest $request)
{
$credentials = $request->validated();
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return to_route('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
```
--------------------------------
### Hybridly Form Submission with Custom Options
Source: https://hybridly.dev/guide/forms
This TypeScript example demonstrates submitting a Hybridly form with options defined at the submission time rather than during initialization. The `submitWith` method allows overriding or specifying the URL and HTTP method dynamically.
```ts
const edit = useForm({
fields: {
body: '',
}
})
edit.submitWith({
url: route('chirps.update'),
method: 'PATCH',
})
```
--------------------------------
### Bulk Action Callback with Collection or Builder with PHP
Source: https://hybridly.dev/guide/tables
Demonstrates defining bulk action callbacks. The first example uses a `Collection` of records, while the second injects a `Builder` instance for more efficient deletion of a large number of records without loading them into memory.
```php
BulkAction::make('delete')
->action(fn (Collection $records) => $records->each->delete())
use Illuminate\Contracts\Database\Eloquent\Builder;
BulkAction::make('delete')
->action(fn (Builder $query) => $query->delete())
```
--------------------------------
### Controller for Hybrid Responses in PHP
Source: https://hybridly.dev/guide/index
Demonstrates how to return hybrid responses from a Laravel controller using the `Hybridly\view` function. This replaces Laravel's standard `view` function for Hybridly-integrated applications. It utilizes type-hinted data objects for passing data to the frontend.
```php
use App\Data\UserData;
use App\Models\User;
use App\Http\Requests\UpdateUserRequest;
use function Hybridly\view;
final class UserProfileController
{
public function show(User $user)
{
return view('users.show', [
'user' => UserData::from($user)
]);
}
public function update(User $user, UpdateUserRequest $request)
{
$user->update($request->validated());
return back()->with('success', 'Changes saved.');
}
}
```
--------------------------------
### Frontend Triggering Backend Partial Loads with Vue.js
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates how to manually trigger the loading of backend partial properties from the frontend using Vue.js and Hybridly. It shows how to use `onMounted` to reload specific properties like 'filters'. Dependencies include `onMounted` from 'vue' and `router` from 'hybridly'.
```vue
```
--------------------------------
### Build UI for Filters with `useRefinements`
Source: https://hybridly.dev/guide/refining
Shows how to use the `refine.filters` property provided by the `useRefinements` composable to dynamically generate a user interface for applying filters. It includes examples for text inputs and select dropdowns for different filter types.
```vue
```
--------------------------------
### Persistent Layouts in Vue (Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Illustrates how to use persistent layouts in Hybridly. The `defineOptions` with `layout` and `properties` allows a view component to utilize a specific layout that maintains its state across navigations.
```vue
Dashboard content
```
```vue
```
--------------------------------
### Configure @unhead/vue with Hybridly
Source: https://hybridly.dev/guide/title-and-meta
Integrate @unhead/vue into your Hybridly application by importing `createHead` and registering it as a Vue plugin in your `main.ts` file. This setup allows for global configuration, such as setting a default `titleTemplate`.
```typescript
import { createApp } from 'vue'
import { initializeHybridly } from 'virtual:hybridly/config'
import { createHead } from '@unhead/vue/client'
initializeHybridly({
enhanceVue: (vue) => {
vue.use(createHead({
init: [
{ titleTemplate: (title) => title ? `${title} - Blue Bird` : 'Blue Bird' }
]
}))
}
})
```
--------------------------------
### Create Hybridly Table Class
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Generates a new table class extending Hybridly's `Table` class using an Artisan command. This class will define the structure, data source, and behavior of your table. It requires a table name and optionally a model name.
```bash
php artisan make:table UsersTable --model=User
```
--------------------------------
### Defining Deferred Properties in PHP
Source: https://hybridly.dev/guide/partial-reloads
Explains how to use the `deferred()` function in PHP to mark properties that should be loaded after the initial page render, improving initial load performance. These properties are automatically fetched via a partial reload once the component mounts.
```php
use function Hybridly\deferred;
return hybridly('foo', [
'slowProperty' => deferred(fn () => $fetchDataFromThirdParty())
])
```
--------------------------------
### Share User Data with Hybridly (PHP)
Source: https://hybridly.dev/guide/authentication
This PHP code demonstrates how to share user data with Hybridly by defining a middleware to expose selected user properties. It uses a Data Transfer Object (DTO) to structure the shared data, ensuring only necessary information is exposed. This improves security and performance by avoiding the exposure of the entire user model.
```php
// app/Http/Middleware/HandleHybridRequests.php
public function share(): SharedData
{
return SharedData::from([
'security' => [
'user' => UserData::optional(auth()->user()),
],
]);
}
// App\Data\UserData
final class UserData extends Data
{
public function __construct(
public readonly string $hashid,
public readonly string $username,
public readonly string $display_name,
public readonly ?string $profile_picture_url,
public readonly ?Carbon $identity_verified_at,
public readonly string $email,
) {
}
}
```
--------------------------------
### Generating Typed URLs in Vue Components with Hybridly (Vue)
Source: https://context7.com/context7/hybridly_dev_guide/llms.txt
Demonstrates how to use the `route` function from Hybridly in Vue components to generate type-safe URLs. It shows generating URLs for the index route and a specific user profile route with parameters.
```vue
HomeUser Profile
```