DEV Community 👩‍💻👨‍💻

Snehal Kadwe
Snehal Kadwe

Posted on

How to create dynamic rows of table in Laravel

Hello Readers,

In laravel while designing blade file for PDF we require plain CSS only we cannot use any frameworks like bootstrap, tailwind CSS, Bulma, etc., and at same time to show data by grid system we have to use table.

But in some cases we require the rows of the table where the first row required the two columns and the second row requires three columns, this is possible when the data is static but it gets complicated when we have the dynamic.

To do that we use modulo operator (%) through which we can define these type of rows.

Refer the below code for better understanding.

$students = [
  {
    name: John,
    last_name: Kim
  },
  {
    name: Lee Min,
    last_name: Hoo
  },
  {
    name: Park,
    last_name: Shin
  },
  {
    name: Nick,
    last_name: J
  },
  {
    name: Kiara,
    last_name: Advani
  },
 {
    name: Jack,
    last_name: Den
  },
];
<table>

            @foreach ($students as $key => $student)
                @if ($key % 2 == 0)
                    echo '<tr class = "pdf-content">';
                @endif

                echo "<td class='width-50px'>
                    <br>
                    <span>
                        <b>Student's Name</b>
                        {{$student->first_name}} {{$student->last_name}}
                    </span>
                    <br>

                    <span>
                        <b>Username</b>
                       {{ $student->username}}
                    </span>
                    <br>

                    <span>
                        <b>Password</b>
                        {{$student->student_unhashed}}
                    </span>

                   </td> ";

                @if ($key % 2 == 1)
                    echo '</tr>';
                @endif
            @endforeach

        </table>
Enter fullscreen mode Exit fullscreen mode

Thank you for reading 🦄

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.