Laravel 5.7 — Sending Data to Your Views

This article will show you how to send data to your laravel view. So let’s get started. For example, let’s say when a user accesses the homepage, we want to send some data to it for them to view. Head over into your code editor and go to routes/web.php — this is where we will be passing in the data for now by hardcoding it in.

Inside the route get for the homepage we need to create a variable and pass in some tasks as an array. So take a look at the code below to see the tasks that have been created.

Route::get(‘/’, function () {
$tasks = [
‘Build header of the website’,
‘Build footer of the website’,
‘Build the homepage template’,
];
return view(‘welcome’);
});

If we access the homepage, nothing is going to happen in regards to the tasks data being passed through. We haven't returned this yet. Next, you need to call tasks in the return function.

return view(‘welcome’, [
‘tasks’ => $tasks
]);

Remember to pass this in as an array. We’re nearly there, head over to the welcome.blade.php file and inside a foreach loop, we will render the tasks that we’ve hardcoded in.

<ul class=”tasks-list”>
@foreach ($tasks as $task)
<li class=”task-item”><?= $task ?></li>
@endforeach
</ul>

Remember to use the blade syntax and not the standard PHP foreach loop. Either way will work, but it’s best to get accustomed to the correct syntax when using Laravel. So here we are cycling through the array of tasks that have been assigned to the $tasks variable & rendering those items into an unordered list. Here is the outcome when you reload the homepage.

The tasks list has now been passed into the homepage view.

If you add another task to the array in the routes file, that will show up here. Fairly simple isn’t it? We can also change the way we call out the $task in the list without using the PHP shorthand syntax;

<li class=”task-item”>{{ $task }}</li>

We’ve now replaced <?= ?> with the double curly braces. I prefer this, it just looks loads cleaner and easier to read. Always look at ways to simplify the code if you can.

We can also pass in as many variables as we want when we are returning the tasks on the homepage view. We just need to add another line of code and then call the variable in our blade file.

return view(‘welcome’, [
‘tasks’ => $tasks,
‘sitename’ => ‘Laravel’
]);

I’ve just created a variable called sitename for now. In the blade file, this is how I’ve called that variable.

<h1>{{ $sitename }} — Homepage</h1>

Simple and straightforward. Don’t you just love it? We can fetch anything from the query string, let me show you how to do this. We ain’t finished just yet. There’s more goodness to showcase here. Let’s create a request;

‘title’ => request(‘title’)

We now need to go back to the homepage and enter the following into the URL after the homepage URL.

http://laracasts.local/?title=Laracasts

So what happens when you pass in the word Laracasts? Below is the result of requesting something from the query string;

We’ve requested the title Laracasts and rendered that on the page.

The curly braces in Laravel escape the data and render what’s left on the page. This is brilliant, we want to make sure no malicious data is being passed through. For example, if we try passing in script tags into the variable that we have created, do you think that will render a script on the page?

‘title’ => ‘<script>alert(“Hello — I love laravel”)</script>’

The outcome is that the script was not executed as a script, whatever was passed into the variable has been stripped out.

<h1>&lt;script&gt;alert(&quot;Hello — I love laravel&quot;)&lt;/script&gt; — Homepage</h1>

And there you have it, the script has been stripped down and rendered. So you may ask, how do I make sure a script acts as a script? We can use !! exclamation points on either side of the curly braces. This is what it should look like.

<h1>{{!! $title !!}} — Homepage</h1>

If you refresh the homepage now, the script will be initialised and will successfully run.

Voila — our script alert is now working!

I’ve mentioned that we should always look at ways to simplify our code. When we are returning the tasks variable to our view, it looks a little messy to me. We can pass that data to our view with one line of code, yes, just one!

return view(‘welcome’, [
‘tasks’ => $tasks,
‘title’ => request(‘title’)
]);

The above code is now going to be simplified into one line.

return view(‘welcome’)->withTasks($tasks)->withTitle('Laracasts');

We can pass in the two functions and within those pass in the variable & string. We can inline the tasks in the return function if you want to. There are different ways we can pass in the tasks.

Route::get(‘/’, function () {
return view(‘welcome’)->withTasks([
‘Build header of the website’,
‘Build footer of the website’,
‘Build the homepage template’,
‘Build the contact form’,
]);
});

I prefer this way. Whichever way works for you that’s fine, there is no right or wrong way.


Using compact() in Laravel

The function compact is widely used in Laravel, don’t confuse this with a Laravel function because it’s not, this is a PHP function. You can see more information on this over HERE. So with() allows you to pass variables to a view and compact() creates an array from existing variables given as string arguments to it.

Below is an example of how we’d use the compact function.

$user = User::all(); 
return view('index', compact('user'));

Here is another example where we are passing the name into our view surrounded by HTML. This will output the name Joe Bloggs on the home view.

Route::get('/', function () {
return view('greeting', compact(['name' => 'Joe Bloggs']));
});
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>

That’s it, you now should understand how to send data to your views. In the next article, we will be looking at “Controllers”. I hope you’ve enjoyed this article, give it a clap and share. If you have any comments, feel free to use the comments section or get in touch with me on my Twitter. Don’t forget to have a look at my previous articles;

Laravel — Getting Started — Installing Laravel 5.7 on Windows
Laravel — Basic Routing

Laravel — Blade Layout Files

Thank you.