Display data in table using foreach in Laravel

There are many ways to display data in a table using the foreach method in Laravel. We have to use an appropriate way to display data into a table so that it does not throw any exception while data goes through the foreach loop. To avoid these exceptions we have to first check if their records exist in it or not and after that, we can display data in it.

Answers 2
  • Display data using count method on object with foreach in table

    --PATH resources\views\<yourfile>.blade.php
    @if($posts->count())
        @foreach($posts as $post)
            <tr>
                <td> {{ $post->title }} </td>
                <td> {{ $post->body }} </td>
            </tr>
        @endforeach
    @else
        <tr>
            <td colspan="2"> No record found </td>
        </tr>
    @endif
    
    0

    The count() method first checks if the object has any records or not, after that, it displays data in the table using the foreach method if the object has records in it. If the object does not have any records then it executes the else statement and displays no records found.

  • Display data in table using forelse loop Laravel

    --PATH resources\views\<yourfile>.blade.php
    @forelse($posts as $post)
        <tr>
            <td> {{ $post->title }} </td>
            <td> {{ $post->body }} </td>
            <td> {{ $post->created_at }} </td>
        </tr>
    @empty
        <tr>
            <td colspan="3"> No record found </td>
        </tr>
    @endforelse
    
    0

    This code snippet is the shorter way to display data in the table using forelse loop in Laravel which displays data if any records exist in object else it displays no record found.

  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet