Laravel Tag Helper

Laravel Tag Helper

Laravel Tag Helper is a package by Marcel Pociot for adding powerful HTML tag helpers to your Laravel application. As a quick example of what this package can do, it ships with a few helpers out of the box.

You might have a typical form with a hidden CSRF input:

<form method="post" action="/profile">
    @method('PUT')
    @csrf
</form>

With the Laravel Tag Helper package you can write the same as follows:

<form csrf method="put">
  {{-- ... --}}
</form>

The output will look like you’d expect:

<form method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="csrf-token">    
</form>

Another built-in helper is the link helper:

<a route="home">Home</a>
<a route="profile" :route-parameters="[$user->id()]">
  Home
</a>

Custom Tag Helpers

The package works by registering tag helpers in a service provider’s boot() method. You can target specific elements and attributes that will trigger a process() call on the helper class during rendering.

Here’s an example from the project’s readme:

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomTagHelper extends Helper
{
    protected $targetAttribute = 'custom';

    protected $targetElement = 'div';

    public function process(HtmlElement $element)
    {
        // Manipulate the DOM element
    }
}

Within the process() method you can customize the HTML element tag. For example, if you had a custom element that you wanted to render as a link:

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomLink extends Helper
{
    protected $targetElement = 'my-custom-link';

    public function process(HtmlElement $element)
    {
        // Example
        // <my-custom-link></my-custom-link>
        $element->setTag('a');
        $element->setAttribute('href', 'https://laravel-news.com');
    }
}

Learn More

You can learn more by checking out the official readme on GitHub or installing the composer package with composer require beyondcode/laravel-tag-helper.


Filed in: Laravel Packages


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
In-house Laravel Developer.
Gold Coast / Australia
MXstore
Laravel Developer
Oak Brook, IL
Tidal Commerce
Senior Backend Engineer
Santa Monica only
Saatchi Art
Senior Laravel Developer
San Francisco
Stitch Labs
Senior Software Developer
South Jordan, UT
Lendio
Full-Stack Developer
Paris, France
Wingly