How to use a foreach loop in php/blade for laravel?

by herminia_bruen , in category: PHP Frameworks , 9 months ago

How to use a foreach loop in php/blade for laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 9 months ago

@herminia_bruen 

In Laravel's Blade templating engine, you can use the @foreach directive to loop through arrays or collections. Here's an example of how to use a foreach loop in Blade for Laravel:

  1. If you have an array of items in your controller, you can pass it to your Blade view like this:
1
return view('your-view')->with('items', $items);


  1. In your Blade view file, you can use the @foreach directive to loop through the items array like this:
1
2
3
@foreach($items as $item)
    <p>{{ $item }}</p>
@endforeach


In this example, $items is the array that contains the items you want to loop through, and $item is the variable that represents each item in the array during each iteration of the loop. You can access each item's value using {{ $item }}.

  1. You can also use Blade's @endforeach directive to end the foreach loop:
1
2
3
@foreach($items as $item)
    <p>{{ $item }}</p>
@endforeach


That's it! You have now successfully used a foreach loop in Blade for Laravel.