DEV Community

Cover image for How to use a loop in blade files - Laravel
Stefan Caky
Stefan Caky

Posted on

2 2

How to use a loop in blade files - Laravel

Introduction

When we talk about the loop in the blade, we mean PHP array passed into HTML template what called blade in Laravel. There is some way to loop in the blade. I will show you the easiest way, with the controller.

Let's go

When we successfully installed the new Laravel application we will create Controller called ProjectsController.

php artisan make:controller ProjectsController -r
Enter fullscreen mode Exit fullscreen mode

Now we get all rows from the database under the Projects column. We use the Project model to get it. Save all projects into the $projects variable then we pass it into the blade template.

use App\Models\Project;

public function index()
    {
        $projects = Project::all();

        return view('projects', ['projects' => $projects]);
    }
Enter fullscreen mode Exit fullscreen mode

Create blade file in view folder called project.blade.php and we use @foreach to loop over the $project variable what we got from ProjectsController using table structure to format the results.

<table class="table table-bordered" >
   <thead>
      <tr>
         <th>Project Title</th>
         <th>Project description</th>
         <th>Created</th> 
      </tr>
   </thead>

   <tbody>
      @foreach($projects as $project)
         <tr>
            <th>{{ @project->title }}</th>
            <th>{{ @project->description }}</th>
            <th>{{ @project->created_at }}</th>
         </tr>
      @endforeach
   </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Conclusion

See how easy to use the loop method in Laravel? When we just pass some array from the controller into blade file.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay