Forte: Parse &amp; Rewrite Laravel Blade Templates | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. [Laravel](https://www.msaied.com/public/articles?category=laravel)
6. /
7. Forte: Parse and Rewrite Laravel Blade Templates with a Typed Syntax Tree

   [Laravel](https://www.msaied.com/public/articles?category=laravel) [Composer Pacakge](https://www.msaied.com/public/articles?category=composer-pacakge) 

 Forte: Parse and Rewrite Laravel Blade Templates with a Typed Syntax Tree
==========================================================================

 Forte is a PHP 8.2 package that parses Blade templates into a typed syntax tree, lets you query nodes with XPath or collection methods, and rewrites files safely — without touching strings, comments, or attributes you never meant to change.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 1 Sep 2026 · Updated 2 Sep 2026 · 4 min read

ShareCopy linkCopied

 ![Forte: Parse and Rewrite Laravel Blade Templates with a Typed Syntax Tree](https://cdn.msaied.com/623/486e2dce5130f1082093684a345ce5ef.png) 

  On this page +1. [What Is Forte?](#what-is-forte)
2. [Installation](#installation)
3. [Parsing Blade Files](#parsing-blade-files)
4. [Querying the Tree](#querying-the-tree)
5. [Rewriting Templates](#rewriting-templates)
6. [Practical Use Cases](#practical-use-cases)
7. [Auditing Views Before Deleting a Component](#auditing-views-before-deleting-a-component)
8. [Bulk Codemods](#bulk-codemods)
9. [CI Convention Checks](#ci-convention-checks)
10. [Ecosystem: Chisel and Reload](#ecosystem-chisel-and-reload)
11. [Key Takeaways](#key-takeaways)

 What Is Forte?
--------------

Forte (`fortephp/forte`) is a Laravel package written by John Koster that parses `.blade.php` files into a typed syntax tree. Instead of running a regex or a `sed` one-liner that blindly matches every occurrence — including ones inside comments, strings, and unrelated attributes — Forte gives you a structured document you can query and rewrite with precision.

Version 3 of `prettier-plugin-blade` (Chisel) is built on Forte, and the project reports it formats complex real-world templates 140 times faster than the previous version.

Installation
------------

Forte requires PHP 8.2, the `ext-dom` extension, and Laravel 10–13:

```bash
composer require fortephp/forte

```

The service provider auto-registers, so the `Forte` facade is available immediately.

Parsing Blade Files
-------------------

```php
use Forte\Facades\Forte;

$doc = Forte::parse('Hello, {{ $name }}!');
$doc = Forte::parseFile('resources/views/welcome.blade.php');

```

Both methods run a lexer and a tree builder. If a template has an unclosed tag or an `@if` with no `@endif`, the parser records a diagnostic and returns a partial tree — the other files in your project still parse normally. Rendering a parsed file back without changes produces identical bytes, whitespace included.

Querying the Tree
-----------------

Query methods return lazy Laravel collections:

```php
$forms        = $doc->queryElements('form');
$conditionals = $doc->queryBlockDirectives(['if', 'unless']);
$components   = $doc->queryComponents(['x-alert', 'livewire:*']);

```

Forte builds a `DOMDocument` internally and exposes XPath queries. Blade constructs become elements in a `forte` namespace, so `@if` is `forte:if` and `{{ }}` echoes are `forte:echo`:

```php
$divs        = $doc->xpath('//div[@class]')->get();
$conditionals = $doc->xpath('//forte:if')->get();

```

Matches come back as Forte nodes, not raw `DOMElement` objects, so you can pipe them straight into a rewrite.

Rewriting Templates
-------------------

`rewriteWith()` accepts a closure that receives a `NodePath` — an object that exposes the node's parent, siblings, ancestors, depth, and mutation methods:

```php
use Forte\Rewriting\NodePath;

$newDoc = $doc->rewriteWith(function (NodePath $path) {
    if ($path->isTag('a') && str_starts_with($path->getAttribute('href') ?? '', 'http')) {
        $path->setAttribute('target', '_blank');
        $path->setAttribute('rel', 'noopener noreferrer');
    }
});

echo $newDoc->render();

```

Edits are queued and applied in a single pass, so a large template produces one new document rather than one per mutation. For longer logic, write a `Visitor` class with `enter()` and `leave()` methods. A `Builder` helper creates new nodes to insert:

```php
use Forte\Rewriting\Builders\Builder;

Builder::element('div')->class('wrapper')->text('Hello');
Builder::directive('if', '($show)');

```

Practical Use Cases
-------------------

### Auditing Views Before Deleting a Component

```php
$uses = Forte::parseFile($file->getPathname())
    ->queryComponents(['x-alert'])
    ->count();

```

Unlike `grep`, this count excludes mentions inside comments, `@php` strings, and unrelated class attributes.

### Bulk Codemods

Adding `loading="lazy"` to every `` without that attribute across hundreds of views is a single `rewriteWith()` pass. An `` inside a comment parses as a different node kind, so `isTag('img')` is false for it — no accidental matches.

### CI Convention Checks

```php
$missing = Forte::parseFile($file->getPathname())
    ->xpath('//form[@method="POST"][not(.//forte:csrf)]')
    ->count();

```

That XPath expression finds every `POST` form with no `@csrf` anywhere inside it. Drop it in a Pest or PHPUnit test to fail the build automatically.

Ecosystem: Chisel and Reload
----------------------------

- **Chisel** (`prettier-plugin-blade` v3) — Blade formatter built on Forte; requires Node 18+.
- **Reload** (`fortephp/reload`) — experimental Vite plugin that patches Blade changes into the page without a full refresh, falling back after a configurable number of incremental patches.

Key Takeaways
-------------

- Forte parses Blade into a typed syntax tree, avoiding false positives that plague regex-based tools.
- XPath queries use a `forte:` namespace for Blade-specific constructs (`forte:if`, `forte:echo`, `forte:csrf`, etc.).
- Rewrites are non-destructive: `rewriteWith()` returns a new `Document` and leaves the original intact.
- Partial parse results and diagnostics mean one broken template never blocks the rest of your codebase.
- Best suited for structure-dependent rules, large-scale codemods, and automated CI checks — not for one-off renames where `sed` is faster.

Forte is MIT licensed and currently at v1.1.0. Source and docs: [fortephp.com](https://fortephp.com) | [GitHub](https://github.com/fortephp/forte).

---

*Source: [Forte: Parse and Rewrite Laravel Blade Templates — Laravel News](https://laravel-news.com/forte-blade-parser)*

- [Laravel](https://www.msaied.com/public/articles?search=Laravel)
- [Blade](https://www.msaied.com/public/articles?search=Blade)
- [Parser](https://www.msaied.com/public/articles?search=Parser)
- [Codemod](https://www.msaied.com/public/articles?search=Codemod)
- [PHP](https://www.msaied.com/public/articles?search=PHP)
- [Packages](https://www.msaied.com/public/articles?search=Packages)

 Frequently asked questions 
---------------------------

  How is Forte different from using grep or sed to find and replace Blade template content?Forte parses templates into a typed syntax tree, so queries and rewrites only match real rendered nodes. A grep or sed command also matches occurrences inside comments, PHP strings, and unrelated attributes. Forte's `isTag()` and XPath queries are false for those node kinds, eliminating accidental matches.

   Does Forte break if a Blade template has a syntax error?No. When the parser encounters an unclosed tag or an unmatched directive like `@if` without `@endif`, it records a diagnostic on the document and returns a partial tree. The rest of your templates parse normally, and you can still query and rewrite the partial tree.

   When should I use a Visitor class instead of a rewriteWith() closure?Use a closure for short, self-contained changes. Write a Visitor when the logic is longer or needs both `enter()` (before children are visited) and `leave()` (after children are processed) hooks — for example, when a change depends on what happened to a node's children.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleMKSine: A Filament CMS with Plugins, Themes, and Blocks for Laravel](https://www.msaied.com/public/articles/mksine-a-filament-cms-with-plugins-themes-and-blocks-for-laravel) [Next articleFilament v3 Table Tricks: Deferred Loading, Live Search, and Custom Filter Forms](https://www.msaied.com/public/articles/filament-v3-table-tricks-deferred-loading-live-search-and-custom-filter-forms)  

   On this page
-------------

1. [What Is Forte?](#what-is-forte)
2. [Installation](#installation)
3. [Parsing Blade Files](#parsing-blade-files)
4. [Querying the Tree](#querying-the-tree)
5. [Rewriting Templates](#rewriting-templates)
6. [Practical Use Cases](#practical-use-cases)
7. [Auditing Views Before Deleting a Component](#auditing-views-before-deleting-a-component)
8. [Bulk Codemods](#bulk-codemods)
9. [CI Convention Checks](#ci-convention-checks)
10. [Ecosystem: Chisel and Reload](#ecosystem-chisel-and-reload)
11. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
