How to use a loop in blade files - Laravel

stefancoding

Stefan Caky

Posted on December 17, 2021

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.

💖 💪 🙅 🚩
stefancoding
Stefan Caky

Posted on December 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related