How to display elements based on key value in laravel?

Member

by orpha , in category: PHP Frameworks , 2 months ago

How to display elements based on key value in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 2 months ago

@orpha 

To display elements based on a key value in Laravel, you can use the @foreach loop in your Blade view file. Here's an example to demonstrate how you can display elements based on a key value:


Assuming you have an array of data in your controller:

1
2
3
4
5
$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Sarah', 'age' => 30],
    ['name' => 'Michael', 'age' => 28]
];


You can pass this data to your Blade template like this:

1
return view('your-view', compact('data'));


In your Blade template, you can use the @foreach loop to display elements based on a key value. For example, if you want to display only the elements where the age is greater than or equal to 28, you can do the following:

1
2
3
4
5
6
7
@foreach($data as $item)
    @if($item['age'] >= 28)
        <p>Name: {{ $item['name'] }}</p>
        <p>Age: {{ $item['age'] }}</p>
        <hr>
    @endif
@endforeach


This will only display the elements where the age is greater than or equal to 28. You can customize the condition based on your requirements.