Skip to content

Instantly share code, notes, and snippets.

@lavary
Last active August 29, 2015 14:01
Show Gist options
  • Save lavary/e94c10ae3de2e501d4ce to your computer and use it in GitHub Desktop.
Save lavary/e94c10ae3de2e501d4ce to your computer and use it in GitHub Desktop.
Passing data to views without using sequential with() methods in Laravel 4

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment