Send data to views
Send data from Controllers to Views.
Commonly you will like to use your Controllers to handle many things like:
Logic of your app.
Database operations.
Send emails.
Return Views with or without data.
In this example we are going to touch the return data feature.
Go to:
$ app/controllers/UsersController.php
You will see the next code:
<?php
use Libs\BoosterORM\BoosterORM;
class UsersController
{
public function index()
{
$user = 'John Doe';
return view('modules.users.index', 'user', $user);
}
Go to view:
$ resources/Views/modules/users/index.php
And write:
<?php echo $user; ?>
Alternativly if you want to send more than one value to your view, in your controller:
<?php
use Libs\BoosterORM\BoosterORM;
class UsersController
{
public function index()
{
$user = 'John Doe';
$data = [
'Title'=>'Users page',
'user'=>$user
];
return view('modules.users.index', $data);
}
Other way more elegant to send data as array could be using a native function compact() :
<?php
use Libs\BoosterORM\BoosterORM;
class UsersController
{
public function index()
{
$title = 'Users Page';
$user = 'John Doe';
return view('modules.users.index', compact($title, $user));
}
For more details about compact you could go to : PHP.net doc.
Now you could print your data in the view like this:
<?php
echo $title;
echo '<br/>';
echo $user
?>
Or if its an array like data from a database select:
<?php
foreach($users as $key->$value){
echo $user->name;
echo '<br/>';
echo $user->email;
}
?>
Last updated
Was this helpful?