2

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?

Lamar
  • 1,761
  • 4
  • 24
  • 50

3 Answers3

3

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

<x-input :attrs="[ 'type' => 'text', 'placeholder' => 'Search...' ]" />
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
-1

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

Milad
  • 95
  • 2
  • 8
  • Interesting, however why can I send a variable as a variable in a component, but not send an array as a variable the same way? And what's the difference between sending the array name as variable and sending the array directly? – Lamar Sep 19 '21 at 06:43
-1

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