Pass array as attribute in blade custom component

2.6k Views Asked by At

I have defied a generic input component in Laravel like this:

//file: views/components/input.balde.php    
<input  @foreach ($attrs as $attr=>$val)
                {{ $attr }} = "{{ $val }}"
            @endforeach
            >

And I would like to use it as follows in blade templates:

<x-input :attrs="{{ ['type'=>'text', 'placeholder'=>"Search.."] }}" ></x-input>

the thing is when I pass an array object like the example above it seems to break the view, however when I send a variable like this:

@php
    $attributesArray = ['type'=>'text', 'placeholder'=>"Search.."];
@endphp    
<x-input :attrs="$attributesArray" ></x-input>

Is there a way to pass the array as is without having to create a variable and sending it so that I don't add unnecessary @php directive?

3

There are 3 best solutions below

1
Milad On

Hi if I understand right you want to get any array values in the string you just simply can do it but using implode.

<x-input :attrs="{{ implode($attributesArray , " ") }}" ></x-input>

and the $attributesArray variable is just a variable to be sent to the blade it a key value array

2
CodeWithKyrian On

Try this
<x-input :attrs="{!! [ 'type' => 'text', 'placeholder' => 'Search...' ] !!}" />

0
ruleboy21 On

Just pass in the array without the double curly braces {{ }}

<x-input :attrs="[ 'type' => 'text', 'placeholder' => 'Search...' ]" />