简体   繁体   中英

Laravel Blade Undefined Variable Error But The Variable Is Defined

This is a really odd error. In my blade view:

    <?php //dd($site); ?>
    @if($site==='site1')

On the second line @if($site==='site1') I get a Undefined variable: site error. But if I uncomment out the dump and die I get the $site variable set. It's literally on the very next line that it tells me it doesn't have a set $site variable in blade. Is my syntax wrong on the if statement?

It looks correct to me, the documentation gives:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Adding a space between @if and the first paren ( made no difference.

I tried clearing the view cache but that made no difference too. Every other change gets registered, for example if I remove the $ that prepends the variable name I get an undefined constant error. I'm developing locally.

I'm at a complete loss because even though the variable is three levels deep in blade I am passing it correctly and I confirmed it with the dump and die. The conditional just won't pick it up.

I pass it into the view like this:

 @component('pages.common.component.mycomponent',['site'=>$site])  
 @endcomponent

And one more level up like this:

 @component('pages.common.parent.mycomponent',['site'=>'site1'])  
 @endcomponent

Any ideas I would be very grateful for!

EDIT:

The dd() call outputs:

"site1"

As a string.

The answer was later in the 2nd level (parent to the component in which I had the error) there were TWO declarations to this third component, one of which was not passing the $site variable. Of course, because I was using an inline dd() method of debugging in the third component it didn't make sense at first, as it hit the first declaration but not the second.

What helped me was calling the render method on the entire view and outputting it as a string, so I could see it was there in the first declaration but not in the second.

So in the controller, instead of:

return view('pages.routes.parent', $params);

I did:

dd(view('pages.routes.parent', $params)->render()); to get the entire view as one string output to trace where I was missing the data. Inspecting the storage compiled views didn't help as they are partials particular to each component or view.

Note for this to work I had to wrap the @if conditionals in another @if conditional, checking if the $site variable was isset() .

Hope this can help someone else in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM