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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

Retry later
πŸ‘‹ Kindness is contagious

DEV works best when you're signed inβ€”unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay