Home > Mobile >  How to prevent Laravel components $attributes from containing passed in variables starting with :
How to prevent Laravel components $attributes from containing passed in variables starting with :

Time:10-30

I am trying to use laravel attributes with my components like https://laravel.com/docs/9.x/blade#default-merged-attributes. In the example the :message variable is not included in the $attribute list but in my code attributes starting wiht : do (and I don't want them to). Here is the code and the output.

text-with-heading.blade.php

<div {{ $attributes->merge(['class' => "m-4"]) }}>
    <a href="#{{$attributes->get('id')}}">
        <h4 >
            {{ $title }}
        </h4>
    </a>
    {{ $slot }}
</div>

blade file calling component

<x-text-with-heading :title="'Aircrafts'" id="aircrafts" :test="$test">
    <div >
        <p>
              Some text here
        </p>
    </div>
</x-text-with-heading>

Rendered HTML (the issue is title and test appearing as attributes for the parent div)

<div  title="Aircrafts" id="aircrafts" test="whatever $test is">
    <a href="#aircrafts">
        <h4 >
            Aircrafts
        </h4>
    </a>
    <div >
        <p>
            Some text here
        </p>
    </div>
</div>

The issue is that $attributes->merge(['class' => "m-4"]) will also add test="whatever $test is" and title="Aircraft" to the rendered html. So if $test is not a string it causes an error, and it also adds a title attribute that I do not want.

Is there a way to exclude attributes starting with : from the $attributes bag, like it shows in the example in the laravel docs where :message is not included?

CodePudding user response:

You may use: Retrieving & Filtering Attributes

You may filter attributes using the filter method. This method accepts a closure which should return true if you wish to retain the attribute in the attribute bag:

{{ $attributes->filter(fn ($value, $key) => $key == 'foo') }}

For example:

text-with-heading.blade.php

<div {{ $attributes->merge(['class' => "m-4"])->filter(fn ($value, $key) => !in_array($key, ['title', 'test'])) }}>
    <a href="#{{$attributes->get('id')}}">
        <h4 >
            {{ $title }}
        </h4>
    </a>
    {{ $slot }}
</div>

Compiles down to:

<div  id="aircrafts">
    <a href="#aircrafts">
        <h4 >
            Aircrafts
        </h4>
    </a>
    <div >
        <p>
            Some text here
        </p>
    </div>
</div>
  • Related