How to echo array elements in laravel?

Member

by mac , in category: PHP CMS , 23 days ago

How to echo array elements in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 22 days ago

@mac 

In Laravel, you can use the @foreach directive in Blade to loop through an array and echo out its elements. Here's an example of how you can echo array elements in Laravel:

1
2
3
@foreach($array as $element)
    {{ $element }}
@endforeach


In this example, $array is the array that you want to loop through. The @foreach directive loops through each element in the array and the {{ $element }} syntax is used to echo out the value of each element.


You can place this code within a Blade template (a .blade.php file) and pass the array from your controller to the view using the with() method or through the compact function.


For example, in your controller:

1
2
3
4
5
6
public function index()
{
    $array = ['element1', 'element2', 'element3'];

    return view('your-view', compact('array'));
}


Then in your Blade template (your-view.blade.php):

1
2
3
@foreach($array as $element)
    {{ $element }}
@endforeach


This will echo out each element in the array on the page when you visit the corresponding route in your Laravel application.