skip to Main Content

In laravel, I am fetching form data into blade view but I don’t know how there is printing serial number on left upper side of my table, here is the code and screenshot. please help me . I just want to add serial number like 1,2,3…

<tbody>
                    {{ $sl = 1; }}

                    @foreach ($data as $data)
                        <tr>
                            <td>{{ $sl }}</td>
                            <td>{{ $data->category_name }}</td>

                            <td> <a id="edit" class="btn btn-primary" href="">Edit</a>
                                <a onclick="return confirm('Are you sure to delete this category?')"
                                    href="{{ url('delete_category', $data->id) }}" class="btn btn-danger">Delete</a>
                            </td>
                        </tr>
                        {{ $sl ++ }}
                    @endforeach
  </tbody>

 here is the screenshot.

enter image description here

I tried to fix it by using core-php code, and getting this problem

2

Answers


  1. When you use curly brackets in Laravel’s Blade it’s an equivalent of echo() in PHP. To fix this change your curly brackets to @php and @endphp.

    <tbody>
        @php $sl = 1; @endphp
        @foreach ($data as $data)
           <tr>
               <td>{{ $sl }}</td>
               <td>{{ $data->category_name }}</td>
           </tr>
           @php $sl++ @endphp
        @endforeach
    </tbody>
    

    Even better if your $data variable is just a list or a collection, don’t use in-template variables. Just iterate:

    <tbody>
        @foreach ($data as $index=>$data)
           <tr>
               <td>{{ $index+1 }}</td>
               <td>{{ $data->category_name }}</td>
           </tr>
        @endforeach
    </tbody>
    
    Login or Signup to reply.
  2. You can check blade templates

    <tbody>
        @foreach ($data as $item)
           <tr>
               <td>{{ $loop->index }}</td>
               <td>{{ $item->category_name }}</td>
           </tr>
        @endforeach
    </tbody>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search