Compare variables in Blade [closed]

0

I need to make a comparison between 2 variables:

Controller:

$files = \File::files('images');

foreach ($files as $file) {
    $info[] = pathinfo($file);
}

$books = File::where('status', 1)->select('name')->get();

return view('cataloged.read', compact(['info','books']));

In my view Blade I have something like this:

@foreach($books as $book)
    @foreach($info as $file)
        @if($book->name == $file['basename'])
            <p>Book</p>
        @else
            <p>No Book</p> 
        @endif
    @endforeach
@endforeach

In my database, I only have 4 records:

@if($book->name == $file['basename'])
       <p>Book</p>
@endif
  

Book Book Book Book

But when I increase @else it returns seven ( 7 ) No Book for every Book except the last one that only returns Book .

  

Book - No book 7 times
  Book - No book 7 times
  Book - No book 7 times
  Book

    
asked by Elio 15.07.2016 в 06:25
source

2 answers

2

Based on the comment in which you explain that you want to obtain as a result seven lines of which:

  • 4 are "Book"
  • 3 are "No Book"

This means that you must iterate through the seven files (to get seven results) stored in $info and within this cycle, iterate through the four "books" stored in $books , unless you have a different parameter for Easily locate books without a loop:

@foreach ($info as $file)

    @php $hasBook = false; @endphp

    @foreach ($books as $book)

        @if ($book->name == $file['basename'])
            <p>Book</p>

            @php $hasBook = true; @endphp
        @endif


    @endforeach

    @if (!$hasBook)
        <p>No Book</p>
    @endif

@endforeach

The problem with this solution is that we are defining a variable $hasBook and we are also changing its value, and this should not be the responsibility of the Vista. In my opinion you should review the values you get in $info and% $book and find / establish a more complete relationship in the controller or in a service (or as you have structured your application).

    
answered by 15.07.2016 / 23:52
source
0

I do not really understand the scope of the compact function, but your variable $ info is local to the foreach statement, I think you should first declare it out of this before doing the assignment.

You could also use the with method of the Response, because compact is typical of php, while with belongs to the framework and has better integration with it. It would be something like:

return view('cataloged.read')->with(['info' => $info, 'books' => $books]);
    
answered by 15.07.2016 в 13:57