Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vrushalrt's avatar

How to work with Views without using PHP's "compact" function.

I'm working on laravel to fetch data from database and store that data or array of data into the variable like $tasks store data of tasks table from database up till everything is fine but during processing the $task variable it is necessary to use "compact" function ?

And can anyone explain this

Route::get('/test', function () {
   
    $data   =   [
                    'name'  =>  'Vrushal',
                    'last'  =>  'Raut',
                    'tasks' =>  [
                                    'Programming',
                                    'UI/UX Developement',
                                    'Cloud Expert'
                                ]
                ];
                //return view('templates/test', compact($data)); //NOT WORKING
                //return view('templates/test', $data); // ITS WORKING
                return View::make('templates/test',$data); // ITS WORKING
}); 

As well as with Database plz explain this

Route::get('/tasks', function(){

    $tasks  =   DB::table('tasks')->get();

    return view('templates/tasks', compact('tasks')); // ITS WORKING
    //return View::make('templates/test',$tasks); // NOT WORKING
});

Thanks in advance! :+1:

0 likes
1 reply
willvincent's avatar
Level 54

All compact does is combine one or more variables into an array keyed by those variable names. So if you're already building up that array on your own, then no you don't need to use compact, just pass the array directly.

So when you have a variable $tasks and then you pass compact('tasks') to the view what it's really doing is taking the value of your tasks variable, and assigning that as a keyed value of an array:

$tasks = 'some data here..';

// If you then do:
$foo = compact('tasks');

// $foo becomes:
// [
//    'tasks' => 'some data here..'
// ]

Then within your view, that array is unpacked into separate variables for each of the top level keys.. So if you pass an array like this to a view:

[
  'foo' => 'bar',
  'bar' => 'baz',
  'baz' => [
    'foo',
    'bar',
    'baz',
  ],
];

Within the view you'll have access to variables: $foo, $bar, and $baz

So, the answer to your question, "is using compact() necessary?" is... it depends. Strictly speaking, no it's not necessary, but if all you're doing is grabbing a collection, and you want that collection accessible by the variable name (as in your second example) is makes a hell of a lot more sense to say:

return View::make('something', compact('tasks'));

Than to do something like this:

return View::make('something', ['tasks' => $tasks]);

or

$data = [
  'tasks' => $tasks,
];

return View::make('something', $data);

Though all of those will yield the same result. :)

Please or to participate in this conversation.