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

//controller

       public function showUser($id)

       {

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

           $name = $user→name;

          $age = $user→age;

          return view(’user.show’,compact(’name’,’age’));

        }

//blade

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

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

//controller

       public function index()

       {

             $users = User::all( );

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

        }

//blade

@foreach ( $users as $user )

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

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

@endforeach

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

Note:

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