Compact() Function

Compact is a php function

compact() function is used to create an array containing variables and their respective values. This function take variable names as its parameters and returns an array where the key are the variable names and the values are the variable values .It’s commonly used to pass data to views in laravel.

eg: 1


       public function showUser($id)


           $user = User::find($id);

           $name = $user→name;

          $age = $user→age;

          return view(’’,compact(’name’,’age’));



<p>Name: {{ $name }}</p>

<p>Age: {{ $age }}</p>
eg: 2


       public function index()


             $users = User::all( );

            return view(’user.index’,compact(’users’));



@foreach ( $users as $user )

<p>{{ $user→name }}</p>

<p>{{ $user→age }}</p>


By using compact( ), you can pass the $users variable to the view in a concise manner, making easily accessible within the view template.


Because variable variables may not be used with PHP’s Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

2 thoughts on “Compact() Function”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top