Search code examples
laravelmodel-view-controllercomponentslaravel-bladelaravel-11

Passing data to an anonymous component


I am a bit confused with the anonymous components.

I am trying to pass a data in the component using prepending : before the attribute. However, it throws me an error

Undefined variable $sizes

But as you can see, I have passed it in the component.

Currently, I am using it and wanted to pass the variable with a data in the sub anonymous component.

So the tree goes something like this. Assuming that the layout/x-layout blade file contains the header and the navbar for my website and I do have this user_preference blade file.

user_preferance.blade.php

<x-layout>
   @if ($counter > 0)
     <x-with_sizes_section :sizes="$sizes" />
   @else
   <x-without_sizes_section />
    @endif
</x-layout>

under the user_preference blade file, I can access the data from the controller. so if I say

<h1> {{ $sizes}} </data>

under the user_preference blade file, it will display it.

I created a separated component for the forms, so as you can see above I have conditional statement, wherein I have to show two different forms depending of the result of the conditional statement.

Now, if it falls under the if statement, I want the

{{ $sizes}} 

to be passed on the anonymous component called with_sizes_section. So as you can see in the code above, I have tried prepending with a : before the attribute name.

I have also tried displaying the data from the user_preference using this one.

user_preferance.blade.php

<x-layout>
   @if ($counter > 0)
     {{ $sizes }}
   @else
   <x-without_sizes_section />
    @endif
</x-layout>

and it displayed the sizes, however I not know why can't I pass it on to another component.

I saw this Verified Answer, however as you can see it is similar already with the code I have provided above.

Any ideas or help are appreciated!


Solution

  • in the with_sizes_section.blade.php add a props in the first line or line number 1 like the code I have provided below.

    @props([sizes])
    <div>
       @foreach($sizes as $size)
          {{ $size }}
       @endforeach
    </div>
    

    then now you can access or fetch the data from the parent