Passing data into a view with laravel

In our web app, we will usually need to display some kind of data from our database or other
data store. In Laravel, we can easily pass that data into our views.

Getting ready

For this recipe, we need to have completed the Creating and using a basic view recipe .

How to do it…

To complete this recipe, follow these steps:
1. Open the routes.php and replace our home and second routes to include the
following data:
Route::get(‘home’, function()
{
$page_title = ‘My Home Page Title’;
return View::make(‘myviews.home’)->with(‘title’,
$page_title);
});

Route::get(‘second’, function()
{
$view = View::make(‘myviews.second’);
$view->my_name = ‘John Doe’;
$view->my_city = ‘Austin’;
return $view;
});
2. In the view/myviews directory, open home.php and replace the code with the
following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Home Page : <?= $title ?></title>
</head>
<body>
<h1>Welcome to the Home page!</h1>
<h2><?= $title ?></h2>
<p>
<a href=”second”>Go to Second Page</a>
</p>
</body>
</html>
3. In the views/myviews directory, open the second.php file and replace the code
with the following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Second Page</title>
</head>
<body>
<h1>Welcome to the Second Page</h1>
<p> You are <?= $my_name ?>, from <?= $my_city ?>
</p>
<p>
<a href=”home”>Go to Home Page</a>
</p>
</body>
</html>
4. Test the views by going to http://{your-server}/home (where your-server is
our URL) and then clicking on the link.

How it works…

If we want to get data into our views, Laravel offers various ways to accomplish this. We start
by updating our first route by passing a single variable to the view, by chaining the with()
method to View::make(). Then, in the view file, we can access the variable by using
whichever name we chose.
In our next route, we assign View::make() to a variable, and then assign values as the
object’s properties. We can then access those properties as variables in our view. To display
the view, we simply return the object variable.

Leave a Reply

Your email address will not be published. Required fields are marked *