The digital landscape shifted significantly this past Saturday when Laravel Lang fell victim to a sophisticated supply chain attack. This wasn't a standard SQL injection or a cross-site scripting flaw. Instead, attackers utilized compromised credentials to push malicious Git tags on forks, bypassing main branch security checks. This incident serves as a wake-up call for the PHP community, signaling a new era of AI-driven, highly sophisticated repository breaches that target the very tools we trust to build our applications. Autoload malware executes without function calls The most terrifying aspect of the Laravel Lang breach is that the payload executes at the autoload stage. In a standard Laravel application, every request—whether it's a web visit, an Artisan command, or a background job—passes through the public `index.php` file. This file initiates the Composer autoloader. Because the malware was embedded at this level, a developer didn't even need to call a specific function from the compromised package to trigger the attack. Simply having the package installed and loading the site was enough to execute the malicious script silently in the background. Credentials are the primary target Modern attacks have moved beyond simple database drops. This specific breach deployed a "stealer" script designed to scour the environment for high-value targets. It didn't just look for `.env` files; it searched for SSH keys, AWS credentials, and GitHub tokens. The goal is lateral movement: using your local machine or server as a jumping-off point to compromise even larger systems. If you ran `composer update` during the window when these malicious tags were active, your entire development environment—not just your project—should be considered compromised. Stop running naked composer updates The habit of running a blind `composer update` to stay "current" is now a liability. To mitigate risk, you must commit your `composer.lock` file to version control. This ensures that every environment—from staging to production—uses the exact same dependency versions verified by the lead developer. When updates are necessary, perform them selectively. Instead of updating the entire tree, use `composer update vendor/package` to limit changes to a single dependency. This reduces the surface area for
Composer
Products
Laravel Daily's 6 mentions of Composer primarily concern its use in verifying findings against standard PHP dependency management commands and ensuring it is installed for database migration, as seen in videos such as "Ward: New Security Scanner for Laravel (written in Go)".
- 4 days ago
- May 13, 2026
- May 12, 2026
- May 7, 2026
- Apr 20, 2026
Overview Modern API development requires more than just returning JSON. It demands predictability and standardization. Combining the native JSON:API support in Laravel 13 with specialized packages creates a robust ecosystem for building scalable, documented, and filterable interfaces. This setup ensures that front-end clients receive data in a consistent format while providing back-end developers with powerful tools to manage complex queries and documentation without manual overhead. Prerequisites To follow along, you should have a solid grasp of PHP and Laravel fundamentals. Familiarity with Eloquent ORM, RESTful API design, and Composer for package management is essential. Knowledge of the JSON:API specification will help you understand the structural requirements of the response data. Key Libraries & Tools * **Laravel 13**: The framework providing native JSON:API resource support. * **Spatie Query Builder**: A package that handles complex filtering, sorting, and including relationships via URL parameters. * **Scramble**: An automated documentation generator that produces OpenAPI 3.1.0 specifications directly from your code. Code Walkthrough Converting a standard resource to a JSON:API resource in Laravel 13 simplifies the class structure. Instead of manual arrays, you define attributes and relationships. ```php namespace App\Http\Resources; use Illuminate\Http\Resources\JsonApi\JsonApiResource; class BookResource extends JsonApiResource { public function attributes($request): array { return [ 'title' => $this->title, 'price' => $this->price, 'in_stock' => $this->in_stock, ]; } public function relationships($request): array { return [ 'author' => $this->author, ]; } } ``` In the controller, Spatie Query Builder intercepts the request to apply filters. We restrict which fields are queryable for security. ```php public function index() { $books = QueryBuilder::for(Book::class) ->allowedFilters(['title', 'in_stock', 'price']) ->allowedIncludes(['author']) ->get(); return BookResource::collection($books); } ``` Syntax Notes JSON:API requires IDs to be strings, even if they are integers in the database. Furthermore, all model fields must reside within an `attributes` wrapper. Laravel 13 handles this wrapping automatically when you extend `JsonApiResource`. Note the usage of `allowedFilters` in the query builder; it prevents users from guessing column names that shouldn't be exposed. Practical Examples By utilizing Spatie Query Builder, users can perform advanced queries directly through the URL. For instance, `GET /api/books?filter[price]=<45&sort=-price&include=author` returns books cheaper than 45 units, sorted descending by price, with the author data included. This eliminates the need for writing dozens of conditional `if($request->has(...))` statements in your controllers. Tips & Gotchas Scramble generates documentation on the fly without an artisan command, meaning your docs are always in sync with your code. However, ensure you use proper type hinting and docblock comments for Scramble to accurately detect validation rules. When using filters, remember that Spatie Query Builder expects an array syntax like `filter[name]=value`, which might differ from standard query strings.
Mar 31, 2026Overview Modern development workflows require more than just clean code; they demand a foundation that AI agents can interpret. By structuring Laravel projects with a specific 7-step system, you provide LLMs with the context needed to "one-shot" complex features like Telegram bots. This technique minimizes hallucinations and maximizes the effectiveness of tools like Laravel Boost and Codeex. Prerequisites To follow this workflow, you should be comfortable with the PHP ecosystem and terminal-based development. Familiarity with Git version control is essential for managing AI-generated changes. You should also understand the basics of Composer for package management and have a preferred AI-integrated editor. Key Libraries & Tools - **Laravel & Filament**: The core framework and the preferred TALL-stack admin panel for rapid UI development. - **Laravel Boost**: A tool that manages guidelines and skills specifically for AI agents within a repository. - **Cloud Code / Codeex**: AI-powered code editors that interact with the project's markdown guidelines. Code Walkthrough 1. Initialization and Documentation Start by creating a clean project and establishing a documentation folder. AI agents perform better when they have a source of truth for project requirements. ```bash laravel new my-app mkdir docs touch docs/project-description.md ``` 2. Admin Panel and AI Skill Injection Installing Filament provides a powerful UI, but the AI agent won't know how to use it unless the Boost guidelines are refreshed. ```bash composer require filament/filament php artisan filament:install --panels ``` After installation, you must re-run the Boost installer. This step discovers the new package and injects Filament-specific rules into `claude.md` or `agents.md`. ```bash php artisan boost:install ``` Syntax Notes This workflow relies heavily on **Markdown-based guidelines**. The `claude.md` file acts as a system prompt for your editor. By running `boost:install`, you ensure the AI understands Laravel 12 and Filament 5 syntax conventions, preventing it from suggesting deprecated methods. Practical Examples In a real-world Upwork project for a Telegram Bingo bot, this preparation allowed an AI to generate the core game logic in just seven phases. By defining the tech stack as MySQL 8 and Laravel in the markdown docs, the AI correctly handled job queues for drawing numbers every five seconds. Tips & Gotchas - **The Boost Refresh**: Many developers forget that `boost update` is different from `boost install`. Only `install` triggers the discovery of new third-party package guidelines. - **Git as a Frontier**: Always commit after every AI interaction. If the agent generates a broken migration or a messy controller, Git is your only way to safely roll back.
Mar 12, 2026Overview of Visual Annotations Explaining visual changes to an AI agent often involves a clunky workflow of screenshots, manual uploads, and imprecise descriptions. Instruckt changes this by allowing developers to annotate DOM elements directly in the browser. Instead of guessing class names or describing a button's location, you click the element, add a note, and generate a markdown prompt that contains the exact technical context Claude Code needs to execute the change. This precision reduces the "hallucination" factor when AI attempts to style UI components. Prerequisites To follow this workflow, you should be comfortable with basic Laravel development and Tailwind CSS. You also need an AI agent capable of processing markdown context, such as Claude Code. Familiarity with Composer for package management is required for the installation steps. Key Libraries & Tools - **Instruckt-Laravel**: The specific adapter for Laravel applications. - **Instruckt Core**: A framework-agnostic JavaScript core that handles the annotation logic. - **Claude Code**: The CLI-based AI agent that receives the markdown feedback to modify the source code. - **Blade Components**: The templating engine used to inject the annotation toolbar. Implementation Walkthrough Installing the tool requires a quick pull via Composer. Run the following command in your terminal: ```bash composer require joshcirre/instruckt-laravel ``` Once installed, you must register the visual toolbar. In a Laravel environment, you typically place the Blade component at the bottom of your global layout file (e.g., `app.blade.php` or `welcome.blade.php`): ```html <x-instruckt /> ``` This tag renders a floating toolbar on your frontend. When you enter "Annotate" mode, the tool identifies the underlying Tailwind CSS classes and HTML structure of whatever you click. After adding notes, click "Copy Annotations as Markdown." You then paste this directly into your AI terminal. The agent sees a structured list of targeted elements and your specific instructions, allowing it to swap links or adjust font sizes with perfect accuracy. Syntax and Conventions The tool relies on the `x-instruckt` Blade component pattern, which is standard for modern Laravel packages. It intelligently scrapes Tailwind CSS classes from the DOM. If you are using Livewire, Instruckt offers specialized adapters to ensure the toolbar persists across reactive state changes. Tips & Gotchas Always wrap your Instruckt component in an environment check. You likely don't want the annotation toolbar appearing in production. Use a conditional check like `@env('local')` to ensure it only loads during development. If the agent fails to find an element, ensure your classes aren't being obfuscated by a minifier during the build process, as Claude Code needs those class strings to locate the correct line in your source files.
Mar 8, 2026Overview Laravel Blaze is a high-performance Blade compiler designed to eliminate the rendering overhead that plagues modern, component-heavy Laravel applications. As developers move away from global Bootstrap styles toward granular Tailwind%20CSS components, the number of Blade components on a single page has exploded. A typical dashboard might render thousands of nested components, leading to server-side bottlenecks where rendering alone takes hundreds of milliseconds or even seconds. Caleb%20Porzio developed Laravel%20Blaze to solve this specifically for the Flux UI library, though it works with any anonymous Blade component. By utilizing advanced compiler techniques like **memoization** and **code folding**, Blaze can reduce rendering times by over 90%, turning a 1.5-second render into a 6-millisecond flash. It accomplishes this by bypassing the heavy lifting Laravel's core engine usually performs—such as container lookups and view resolution—and transforming components into highly optimized PHP functions. Prerequisites To get the most out of this tutorial, you should have a solid foundation in the following: - **Laravel Basics**: Understanding the request lifecycle and service providers. - **Blade Components**: Familiarity with anonymous components, props, and slots. - **PHP Performance Concepts**: A basic understanding of how `opcache` works and why file system lookups are expensive compared to in-memory operations. - **Composer**: Ability to manage packages via the PHP dependency manager. Key Libraries & Tools - Laravel%20Blaze: The core package that provides the optimized compiler and optimization directives. - Livewire: While not strictly required, Blaze is built by the Livewire team and integrates seamlessly with its reactive patterns. - Flux: A UI component library that heavily utilizes Blaze to maintain high performance despite its complex Tailwind%20CSS structure. - **The Blaze Profiler**: A built-in debugging tool that visualizes component render times and folding status. Code Walkthrough: Implementing Blaze Installation and Basic Setup First, pull the package into your project using Composer. Although it is developed by the Livewire team, it is a standalone Laravel package. ```bash composer require livewire/blaze ``` Once installed, you must opt-in your components to the Blaze compiler. You do this by adding the `@blaze` directive at the very top of your component file. ```php {{-- resources/views/components/button.blade.php --}} @blaze <button {{ $attributes }}> {{ $slot }} </button> ``` When you add `@blaze`, the package intercepts the standard Blade compilation. Instead of Laravel generating a file that performs dozens of `app()->make()` and `view()->exists()` calls at runtime, Blaze generates a plain PHP function. This function accepts props and slots as arguments and returns a string, bypassing the overhead of the Laravel Container entirely. Level 2: Component Memoization If your page renders the same component multiple times with the exact same attributes (like a status badge or a specific icon), you can enable **memoization**. This caches the rendered HTML in memory during a single request. ```php {{-- resources/views/components/status-pill.blade.php --}} @blaze @memo(true) <span class="pill-{{ $type }}"> {{ $label }} </span> ``` By adding `@memo(true)`, Blaze creates a static cache key based on the component name and the serialized props. If you render this component 500 times with the same `type` and `label`, PHP only executes the logic once. The other 499 instances are simple string lookups from an internal array. Level 3: Code Folding and Partial Folding The most aggressive optimization is **Code Folding**. This attempts to "pre-render" the component at compile time rather than runtime. If a component is entirely static, Blaze replaces the component call in your parent view with the actual HTML string during the compilation phase. ```php {{-- resources/views/components/icon.blade.php --}} @blaze @fold(true) <svg ...> ... </svg> ``` When Blaze sees this icon in a parent view, it executes the Blade logic once, takes the resulting HTML, and hardcodes that HTML into the cached PHP file. This effectively deletes the component's runtime cost. For components with dynamic parts, Blaze uses **Partial Folding**. It uses a tokenized parser to identify dynamic variables, replaces them with placeholders, renders the static shell, and then re-inserts the dynamic PHP logic into the resulting string. This allows for nearly static performance even when passing a dynamic `$label` to a button. Syntax Notes: The Tokenized Parser Unlike standard Blade, which uses Regex to find and replace tags, Blaze utilizes a custom **Tokenized Parser**. 1. **Tokenization**: It breaks the source code into a flat list of tokens (Tag Open, Tag Name, Attribute, String, Variable). 2. **AST Construction**: It assembles these tokens into an **Abstract Syntax Tree (AST)**. This tree understands that a `flux:button` contains a `flux:icon` as a child. 3. **Transformation**: Blaze traverses the AST. If it finds a component marked for folding, it executes the render logic. 4. **Code Generation**: It spits out the final, optimized PHP file. This structured approach is what allows Blaze to "know" which parts of a component are safe to hardcode and which must remain dynamic. Practical Examples: Boosting a Dashboard Consider a dashboard with 1,000 table rows, each containing an avatar, a status badge, and an action dropdown. - **Without Blaze**: Laravel performs 3,000+ container lookups and merges thousands of attribute bags. This can easily take 150-200ms. - **With Blaze + Memoization**: The avatar and status badge (often repeated) are memoized. The action dropdown is optimized into a function call. Total render time drops to ~15ms. - **With Blaze + Folding**: The SVG icons within the dropdown are folded away. They no longer exist as PHP logic at runtime. Total render time drops to <10ms. Tips & Gotchas - **Static vs. Dynamic State**: Code folding is a "sharp knife." If your component relies on global state (like `auth()->user()`) but you don't pass that state as a prop, the component might fold based on the user who triggered the compilation. Always ensure folded components are pure functions of their props. - **The Profiler**: Use `BLAZE_DEBUG=true` in your `.env`. This adds a floating button to your UI that breaks down exactly how many milliseconds each component took and why it was (or wasn't) folded. - **The @unblaze Directive**: If you have a specific block within a blazified component that must remain dynamic and escape the optimized compiler's logic, wrap it in `@unblaze`. This is useful for validation errors or CSRF tokens that must be unique per render. - **Anonymous Only**: Currently, Blaze only optimizes anonymous Blade components. Class-based components are not yet supported due to the complexity of their lifecycles and constructor logic.
Feb 24, 2026Overview AI coding assistants rely heavily on context files like CLAUDE.md to follow project standards. However, LLMs often overlook text-based instructions in large files. This tutorial explores shifting these rules from passive documentation to active automation using Laravel tools. By offloading linting, type-checking, and architecture validation to the machine, you ensure 100% compliance while saving valuable context window tokens. Prerequisites To follow this guide, you should be comfortable with the PHP ecosystem and Laravel framework. Familiarity with Composer for package management and basic knowledge of CI/CD concepts like pre-commit hooks will help you implement these automations effectively. Key Libraries & Tools * Laravel Pint: A zero-config PHP code style fixer built on top of PHP-CS-Fixer. * Larastan: A wrapper around PHPStan specifically designed to handle Laravel's magic methods and relationships. * Pest PHP: A testing framework that includes powerful architectural testing capabilities. Code Walkthrough Automating Style with Pint Instead of asking an AI to "always use curly braces," define these in `pint.json`. This ensures the rules are enforced every time you run the tool. ```json { "preset": "laravel", "rules": { "braces": true, "no_empty_comment": true, "no_unused_imports": true } } ``` You can trigger this via a pre-commit hook or directly through Claude Code events to fix styling immediately after the AI edits a file. Enforcing Strict Types with Larastan Move rules regarding return types and type hints out of your markdown files. Larastan catches missing type hints in relationship methods and method signatures far more reliably than an LLM. ```neon phpstan.neon parameters: level: 5 paths: - app checkMissingIterableValueType: true ``` Architectural Tests with Pest Use Pest to prevent developers (and AI) from using forbidden functions or violating folder structures. ```php // tests/ArchTest.php arch('globals') ->expect(['dd', 'dump', 'ray']) ->not->toBeUsed(); arch('app') ->expect('App\Models') ->toOnlyBeUsedIn('App\Repositories'); ``` Syntax Notes When configuring `pint.json`, notice the use of boolean flags to toggle specific PSR standards. In Larastan (and PHPStan), the `level` parameter is your primary lever for strictness; higher levels require more explicit type definitions. Practical Examples By moving 22 lines of text-based rules into these tools, you save roughly 800 tokens per prompt. In a real-world CI/CD pipeline, this setup prevents "style drift" where different AI models might interpret
Feb 23, 2026Overview: The Unified AI Strategy for Laravel Building AI features often feels like a fragmented journey. Developers usually jump between specialized APIs for text, separate services for images, and complex libraries for audio transcription. The Laravel AI SDK changes this by providing a unified, first-party toolkit that handles the heavy lifting of AI integration. It treats AI as a core application concern, much like how Laravel handles databases or queues. By abstracting the differences between providers like OpenAI, Anthropic, and Gemini, it allows you to write cleaner, more maintainable code that isn't locked into a single vendor's API. Taylor Otwell designed the SDK to feel "Laravel-esque." This means leaning into conventions like class-based agents, fluent API chains, and deep integration with the existing Laravel ecosystem. Whether you need to summarize an issue in a project management tool, generate realistic speech via ElevenLabs, or perform semantic search on a mountain of PDFs, the SDK provides the scaffolding to do it efficiently. It moves AI from being an experimental add-on to a standard part of the modern developer's workflow. Prerequisites and Environment Setup Before you begin building, ensure you have a standard Laravel environment ready. You should be comfortable with PHP, Composer, and basic Laravel concepts like controllers and service providers. You will also need API keys from at least one AI provider. While the SDK supports local models via Ollama, production applications typically require keys for OpenAI or Anthropic. To get started, install the package via Composer: ```bash composer require laravel/ai ``` After installation, publish the configuration and migrations: ```bash php artisan vendor:publish --tag="ai-config" php artisan vendor:publish --tag="ai-migrations" php artisan migrate ``` The configuration file (`config/ai.php`) allows you to define your default providers. You can set different defaults for different modalities—for instance, using Claude for text and DALL-E for images. This flexibility is a core strength of the SDK. Key Libraries & Tools * **Laravel AI SDK**: The primary toolkit for interacting with LLMs, image generators, and audio services. * **Prism**: A community package by TJ Miller that serves as the query builder layer for the SDK's text generation. * **ElevenLabs**: Integrated for high-quality text-to-speech capabilities. * **Ollama**: Enables running local models for development and testing without incurring API costs. * **Laravel Boost**: A local MCP server that provides AI agents with context about your specific Laravel codebase. * **PostgreSQL with PGVector**: Used for storing and searching vector embeddings locally. Code Walkthrough: Implementing Agents and Tools 1. Creating an Agent The Agent class is the heart of the SDK. It encapsulates the identity of your AI. Instead of passing long strings of instructions in every controller, you define them once in a reusable class. You can generate one using the Artisan command: ```bash php artisan make:agent SalesCoachAgent ``` In the generated class, you define the system prompt and the models to use. The `instructions` method is where you set the "personality" and guardrails for the agent. ```php namespace App\Agents; use Laravel\AI\Agent; class SalesCoachAgent extends Agent { public function instructions(): string { return "You are an expert sales coach. Analyze the provided transcript and offer three actionable improvements."; } } ``` 2. Using Structured Output One of the most powerful features is getting the AI to return data in a specific format rather than a messy string. The SDK uses a JSON Schema builder to ensure the model follows your rules. This makes it possible to save AI responses directly into your database without fragile regex parsing. ```php use App\Agents\SalesCoachAgent; use Laravel\AI\Schema; $agent = new SalesCoachAgent(); $response = $agent->predict( prompt: "Analyze the call from yesterday.", schema: Schema::object([ 'sentiment' => Schema::string()->description('Overall tone of the customer'), 'score' => Schema::integer()->description('Score from 1-10'), 'follow_up_needed' => Schema::boolean(), ]) ); // Access data directly as an array echo $response['sentiment']; ``` 3. Integrating Tools (Function Calling) Tools allow your AI to actually *do* things. You can give an agent the ability to search the web, fetch a URL, or even query your own database. The SDK comes with several provider tools built-in, but you can also write your own custom tools by extending the `Tool` class and implementing a `handle` method. ```php use Laravel\AI\Tools\WebSearch; class ResearcherAgent extends Agent { public function tools(): array { return [ new WebSearch(), ]; } } ``` When you prompt this agent, it will realize it needs more info, call the `WebSearch` tool, and then use the results to finish its answer. This turns a static LLM into a dynamic assistant. Syntax Notes: Attributes and Traits The Laravel AI SDK makes heavy use of PHP attributes to simplify configuration. These attributes allow you to stay updated with the latest model advancements without changing your code logic. * **`#[UseCheapestModel]`**: Instructs the SDK to use the most cost-effective model for a specific provider (e.g., GPT-4o-mini or Claude Haiku). This is perfect for simple tasks like summarization. * **`#[UseSmartestModel]`**: Forces the use of the flagship model (e.g., Claude 3.7 Sonnet) for tasks requiring high reasoning capabilities. * **`RemembersConversations` trait**: Adding this to your agent automatically manages database storage for chat history, ensuring the AI remembers previous messages without you manually passing a growing array of context. Practical Examples: The 'Larvis' Workflow A practical application of this tech is building a voice-enabled assistant like "Larvis." The workflow demonstrates the multi-modal nature of the SDK: 1. **Transcription**: The user uploads an audio file of their question. The SDK uses a `transcribe` method (typically via Whisper) to convert audio to text. 2. **Context Retrieval**: The agent fetches relevant local documents (like Markdown files) and injects them into the prompt to provide specific knowledge the LLM wasn't trained on. 3. **Inference**: The agent generates a text response based on the transcription and the local documents. 4. **Speech Synthesis**: The text response is passed to the `audio` method, using ElevenLabs to generate a high-quality voice response that is sent back to the user. This entire pipeline, which would previously take dozens of different library integrations, can now be handled in a single Laravel controller using less than 50 lines of code. Tips & Gotchas * **Context Bloat**: Be careful not to attach too many tools or files to every request. Every tool definition and message in a conversation history consumes tokens, which increases latency and cost. Use the `RemembersConversations` settings to prune old messages. * **Failover Logic**: In production, always define a fallback provider. If OpenAI is experiencing downtime or you hit a rate limit, the SDK can automatically switch to Anthropic to keep your app running. * **Local Development**: Use Ollama for your daily coding to save money. You can switch your local `.env` to point the AI provider to `http://localhost:11434` to test your logic for free. * **Async Processing**: For long-running tasks like transcribing a massive video file or generating a complex image, use the `queue` method. This offloads the work to your Laravel worker and prevents your web request from timing out.
Feb 9, 2026Overview Tyro provides a robust, production-ready framework for managing authentication, authorization, and granular roles in Laravel applications. Created by Hasin Hayder, it distinguishes itself from traditional permission packages by offering over 40 Artisan commands and specialized features like user suspension and built-in API authentication routes. It serves as a comprehensive alternative to Spatie Laravel Permission, specifically optimized for API-centric architectures. Prerequisites To follow this guide, you should have a baseline understanding of the Laravel framework, particularly Laravel Sanctum for token-based authentication. You will need a development environment running PHP 8.x and Composer installed. Key Libraries & Tools - **Laravel Tyro**: The primary authorization engine handling roles and privileges. - **Laravel Sanctum**: The underlying dependency used for generating and verifying API tokens. - **Postman**: An API client used to test login endpoints and protected routes. - **VS Code**: The recommended code editor for managing your project files. Code Walkthrough 1. Installation and Scaffolding Begin by pulling the package into a fresh project and running the installation command. This process automatically sets up the necessary API infrastructure. ```bash composer require hasinhayder/tyro php artisan tyro:install ``` 2. Model Configuration Integrate the Tyro functionality into your `User` model by adding the `HasTyroRoles` trait. This enables the model to interact with the underlying role-user pivot tables. ```python namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use HasinHayder\Tyro\Traits\HasTyroRoles; class User extends Authenticatable { use HasTyroRoles; } ``` 3. Protecting Routes with Privileges Unlike standard Sanctum protection, Tyro allows you to gate specific actions behind named privileges. In your `api.php` routes file, apply the `privilege` middleware to sensitive endpoints. ```python Route::middleware(['auth:sanctum', 'privilege:posts.create'])->group(function () { Route::post('/posts', [PostController::class, 'store']); }); ``` Syntax Notes Tyro uses a specific naming convention for its pivot tables, opting for `user_roles` rather than the traditional alphabetical `role_user` format. It also utilizes a "Privilege" nomenclature which is functionally equivalent to "Permissions" in other ecosystems but allows for more granular slug-based checks. Practical Examples In a real-world scenario, you might have an `Admin` role with a `posts.create` privilege. When an Admin logs in via `/api/login`, they receive a token. Sending a POST request to `/api/posts` with this token succeeds. However, a regular user with a valid token but lacking the specific `posts.create` privilege will receive a `403 Forbidden` response, ensuring tight security for your data-writing endpoints. Tips & Gotchas When testing with Postman, always ensure your headers include `Accept: application/json`. Without this, Laravel might attempt to return a standard HTML login redirect rather than a clean JSON error message when access is denied. Furthermore, remember that Tyro relies on its own seeders; ensure you run `php artisan db:seed --class=TyroSeeder` during initial setup to populate the default admin accounts.
Jan 31, 2026Synchronizing AI Logic Managing multiple AI coding assistants like Claude Dev, Cursor, and Open Code often leads to context fragmentation. You define project rules in one tool, but another remains oblivious. Laravel Boost 2.0 solves this by acting as the single source of truth. It synchronizes project-specific logic across all your agents simultaneously, ensuring every tool understands your architectural decisions without manual configuration. Guidelines vs. Agent Skills In earlier versions, Laravel Boost relied heavily on guidelines—global context loaded at the start of every chat. This often bloated the context window and wasted tokens. Boost 2.0 introduces **Agent Skills**, a specialized format based on the emerging Open Code standard. Unlike guidelines, skills load dynamically. Your agent only accesses the Livewire or Pest skill when the current task actually requires that specific expertise. This makes your prompts roughly 40% leaner while maintaining high precision. Implementation and CLI Workflow Setting up Boost 2.0 is straightforward for both new and existing projects. For current applications, use Composer to upgrade the package. If you are starting fresh with the Laravel installer, the setup process now prompts you to configure Boost features immediately. ```bash Add a third-party skill from the community php artisan boost:add-skill remote-dev/remotion Sync changes after manual overrides php artisan boost:update ``` When you add skills, Boost handles the messy work of directory mapping. It knows Claude Dev expects files in `.claudecode/` while others might look in `.ai/`. You manage one `skill.md` file, and Boost distributes it to the correct hidden directories. Custom Overrides and Best Practices Standardized skills are excellent, but your team might have unique conventions. You can override any default skill by mirroring its folder structure within your project's local directory. By placing a custom `skill.md` in your local path and running the update command, you force the AI agents to prioritize your specific instructions over the defaults. For team collaboration, keep your `.ai/` folder in version control but add individual agent folders (like `.claudecode/` or `.cursor/`) to your `.gitignore` to avoid environment conflicts.
Jan 28, 2026Overview Laravel Notify by Arthur%20Mone streamlines the implementation of toast notifications within the Laravel ecosystem. Version 3 introduces refined animations and a variety of visual presets that move beyond standard success or error alerts. It serves as a bridge between backend logic and frontend user feedback, allowing developers to trigger high-quality UI components directly from controllers or components. Prerequisites To implement this package effectively, you should possess a working knowledge of the PHP language and the Laravel framework. Familiarity with Tailwind CSS is necessary for styling, and basic understanding of Blade templates or Livewire will help you place the notification components correctly. Key Libraries & Tools - **Laravel Notify**: The primary package for flash notifications. - **Composer**: The dependency manager used for installation. - **Tailwind CSS**: Utility-first CSS framework required for the notification styles. - **Livewire**: Optional full-stack framework for dynamic interfaces. Code Walkthrough Begin by installing the package via Composer and publishing the configuration assets: ```bash composer require mckenziearts/laravel-notify php artisan vendor:publish --provider="Mckenziearts\Notify\LaravelNotifyServiceProvider" ``` Next, integrate the notification component into your main layout or sidebar within your Blade templates. This component acts as the container for all incoming alerts: ```blade {{-- resources/views/layouts/app.blade.php --}} <x-notify-messages /> @notifyJs ``` To trigger a notification from a controller, use the provided helper methods. The `notify()` function allows you to chain a status and a `send()` call to finalize the action: ```php public function store(Request $request) { // Logic to save data notify()->success('Feedback submitted successfully', 'Success'); return redirect()->back(); } ``` Syntax Notes The package utilizes a fluent API for notification construction. You can swap `.success()` for `.error()`, `.info()`, or `.warning()`. For specialized layouts, use the `connectify` or `emotify` methods which change the visual structure and icon set used in the toast. Practical Examples Beyond simple success messages, Laravel Notify supports "Drakify," which uses specific imagery for internal systems, and "Smiley" notifications for a more friendly user experience. These are particularly useful in administrative dashboards where you want to distinguish between system logs and user-facing feedback. Tips & Gotchas Ensure your Tailwind CSS configuration includes the package's view paths. If the notifications appear unstyled, check that you have imported the `@notifyCss` and `@notifyJs` directives in your layout. Always remember to call `->send()` at the end of your chain to ensure the flash data persists for the next request.
Jan 9, 2026Overview Inertia.js acts as a bridge between the robust backend capabilities of Laravel and the dynamic user interfaces of React. It eliminates the need for complex API development by allowing you to build single-page applications (SPAs) without leaving the comfort of a server-side framework. You get the snappiness of a modern frontend with the routing and controller logic of a traditional monolith. Prerequisites To follow this guide, you should have a solid grasp of PHP and JavaScript. Familiarity with the Laravel directory structure and React component lifecycle is highly recommended. You will also need Node.js and Composer installed on your local machine. Key Libraries & Tools - **Laravel**: The PHP framework providing the backend infrastructure. - **Inertia.js**: The glue that connects the server-side to the client-side. - **React**: The frontend library used for building interactive components. - **Vite**: The build tool that handles asset bundling and hot module replacement. Code Walkthrough 1. Defining Routes In a typical Laravel app, you return a view. With Inertia.js, you return an `Inertia::render` response. This tells the backend to send the necessary component data to the frontend. ```php use Inertia\Inertia; Route::get('/demo', function () { return Inertia::render('DemoPage', [ 'user' => Auth::user(), ]); }); ``` 2. The Root Template You only need one Blade file, usually `app.blade.php`. This file contains the `@inertia` directive, which serves as the mounting point for your frontend application. ```html <!DOCTYPE html> <html> <head> @viteReactRefresh @vite(['resources/js/app.jsx']) @inertiaHead </head> <body> @inertia </body> </html> ``` 3. Middleware Configuration The `HandleInertiaRequests` middleware is the engine room. It manages asset versioning and allows you to share data globally, such as flash messages or authentication states. ```php public function share(Request $request): array { return array_merge(parent::share($request), [ 'auth' => [ 'user' => $request->user(), ], ]); } ``` Syntax Notes Notice the shift from `view()` to `Inertia::render()`. This is a critical pattern. On the frontend, Inertia.js intercepts clicks on links and converts them into XHR requests. This prevents full page reloads while maintaining the browser's back-button functionality and URL state. Practical Examples - **Dashboards**: Ideal for complex admin panels where state must persist between navigation. - **Form Handling**: Use the Inertia form helper to handle validation errors directly from Laravel without manual state management in React. Tips & Gotchas Always use the Laravel installer and starter kits like Breeze or Jetstream. These provide pre-configured authentication and asset pipelines, saving hours of manual setup. If you see a full page reload, verify you are using the `<Link>` component from `@inertiajs/react` instead of standard `<a>` tags.
Dec 23, 2025