简体   繁体   中英

Laravel @foreach and @forelse

I have a problem with my view of laravel. I have a field that executes a loop, and if it has data in the field it list, but if it does not it only shows me nothing.

I used @forelse but it does not work, any help?

with $prices I can check whether or not it has the value, but in that field infos_home does not. I used @forelse but it does not work, any help?

<em>{{ $prices->price ?? ' - ' }}</em> <br>

@forelse($prices->infos_home as $info)
    <em>{{ $info }}</em> <br>
@empty
    <em> - </em>
@endforelse

When I use @forelse I have the following error message.

message: "Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Trying to get property 'infos_home' of non-object (View: C:\wamp64\www\suzuki-cms-backoffice\resources\views\brand\motorcycle\variations\index\column-price.blade.php)"

KISS and just use @if / @else :

<em>{{ $prices->price ?? ' - ' }}</em> <br>

@if($prices && $prices->infos_home)
    @foreach($prices->infos_home as $info)
        <em>{{ $info }}</em> <br>
    @endforeach
@else
    <em> - </em>
@endif

@forelse is good when you are sure that variable exists.

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