Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
communitycreator

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

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring