Trusted answers to developer questions

How to use the compact() method to parse data to views in Laravel

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

There are many methods to pass data, especially data queried from the database.

This shot explains how to use the compact() method to elegantly parse data to your views.

Go to the Controller to implement the method.

When you have several variables with saved data and you want to parse to view, you can use the compact() method.

For example:

$users = User::all();
$posts = Post::all();
return view('/comment',compact('users','posts'));

In the code above, we return the comment view, which should typically be in your resources/views directory as comment.blade.php. We parse the data as a string, in the same fashion as it is written.

To get the data while in the comment view, we use @foreach to loop through the values like so: @foreach($users as $user). Then, end the foreach statement after you are done: @endforeach.

Summary

The compact() method makes it a lot easier to parse data to the view in a readable format.

RELATED TAGS

laravel

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?