Python has a nice built-in function named locals()
which returns a dictionary of local symbol table. This makes it easy to pass local variables to views in a single move.
I was wondering if PHP has such nice feature. I searched PHP's documentation and found this familiar built-in function: get_defined_vars()
get_defind_vars()
Returns an array of all defined variables within the current scope.
Since PHP 5.0.0, the $GLOBALS
variable is included in the results of the array returned.
You can use get_defind_vars()
in a controller,closure or anywhere else you need:
<?php
$users = User:all();
return View::make('users.list')->with(get_defined_vars());
?>
The above block of code gets the list of users in User
model and makes $users
available in users.list
view.
You can also combine Laravel's array_except()
with get_defined_vars()
to exclude data you don't need:
<?php
$date = date('Y-m-d H:i:ds');
$users = User:all();
return View::make('users.list')->with( array_except( get_defined_vars, ['date'] ) );
?>
The second parameter in array_except()
is the list of vars you want to exclude.
Hope This helps someone.
Happy coding.