Home > Net >  laravel php foreach use if div open and close
laravel php foreach use if div open and close

Time:11-27

there is a different structure to show projects Project 1 and 2 are in the same Project 3 is in a different Project 4 and 5 are in the same Project 6 is in a different it goes on like this

div will open if $i == 1

If $i == 2 the div will be closed

If $i == 3 the div will be opened and closed

my code

@foreach($projects as $project)
    @if($loop->iteration % 3 === 0 || $loop->first || $loop->iteration % 2 === 0)
        <div > @endif

            <img src="{{ Voyager::image($project->image) }}" alt="{{ $project->title }}">

            @if($loop->iteration % 3 === 0 || $loop->last || $loop->iteration % 2 === 0) </div>
    @endif
@endforeach

my code result

        <div >
        <img src="project1.jpg" alt="">
        <div >
            <img src="project2.jpg" alt="">
        </div>
        <div >
            <img src="project3.jpg" alt="">
        </div>
        <div >
            <img src="project4.jpg" alt="">
        </div>
        <img src="project5.jpg" alt="">
        <div >
            <img src="project6.jpg" alt="">
        </div>
        <img src="project7.jpg" alt="">
        <div >
            <img src="project8.jpg" alt="">
        </div>
        <div >
            <img src="project9.jpg" alt="">
        </div>

the result i want

    <div >
        <img src="project1.jpg" alt="">
        <img src="project2.jpg" alt="">
    </div>
    <div >
        <img src="project3.jpg" alt="">
    </div>
    <div >
        <img src="project4.jpg" alt="">
        <img src="project5.jpg" alt="">
    </div>
    <div >
        <img src="project6.jpg" alt="">
    </div>
    <div >
        <img src="project7.jpg" alt="">
        <img src="project8.jpg" alt="">
    </div>
    <div >
        <img src="project9.jpg" alt="">
    </div>

CodePudding user response:

You can chunk the collection to two and one items in it respectively:

@foreach ($projects
    ->chunk(3)
    ->map(function ($item) {
        return $item->chunk(2);
    })
    ->flatten(1) as $projectData)
    <div >
        @foreach ($projectData as $project)
            <img src="{{ Voyager::image($project->image) }}" alt="{{ $project->title }}">
        @endforeach
    </div>
@endforeach

CodePudding user response:

@foreach($projects as $project)
@if($loop->first)
    <div > @endif
        

        @if($loop->iteration % 3 === 0) </div>
<div >
        @endif
        <img src="{{ Voyager::image($project->image) }}" alt="{{ $project->title }}">
@if($loop->iteration % 3 === 0) </div>
<div >

@endif
@if($loop->last)
    </div> 
@endif
@endforeach
  • Related