Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel controller compact doesn't work

Tags:

php

laravel

In my Routes I have:

Route::get('/about','PagesController@about');

In PagesController:

public function about()
{
    $people=['Taylor','Matt','Jeffrey'];
    return view('pages.about',compact($people));
}

if I use

return view('pages.about',['people'=> $people]);

It runs ok.

The controller isn't passing the array to view, why ?

like image 641
Diego Silveira Mota Avatar asked Jun 07 '26 05:06

Diego Silveira Mota


2 Answers

Use compact('people')

If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.

like image 99
AshanPerera Avatar answered Jun 10 '26 03:06

AshanPerera


Remove $ sign inside compact function like compact('people'). This will solve your issue.

compact() is not a Laravel function. It is a PHP function. It creates an array containing variables and their values.

For an example, assume you have following variables.

$name = 'Jon Snow';
$dad = 'Rhaegar Targaryen';
$mom = 'Lyanna Stark';

If you put those in a compact() as follows,

$thePrinceThatWasPromised = compact(['name', 'dad', 'mom']);

You'll get following array assigned to $thePrinceThatWasPromised.

[
    'name' => 'Jon Snow',
    'dad' => 'Rhaegar Targaryen',
    'mom' => 'Lyanna Stark'
]

For more information go to php manual

like image 23
Manish Avatar answered Jun 10 '26 05:06

Manish