DEV Community

Cover image for Laravel101: How to pass data between views in your web pages
Kazem
Kazem

Posted on • Originally published at kazemm.dev

Laravel101: How to pass data between views in your web pages

Hey there! In the last tutorial, we talked about the web.php file. It's basically where all the routes and requests for your app are defined. By using web.php, you can create routes that show users a simple text output in their browser. Pretty cool, right?
In this tutorial, we'll learn how to create a simple view in Laravel. We'll also explore how to create routes that point to our views, and how to pass data from our controllers to our views.


What are views in Laravel?

Views in Laravel are files that contain HTML and CSS code that are rendered in the browser. They are used to define the layout and structure of a web page. In Laravel, views are located in the resources/views directory.
To create views, you gotta go to /resources/views in the main directory of your project. Once you're there, you'll see a file called welcome.blade.php. This is the same page we saw during the first tutorial when we installed Laravel.
Now, here's something cool: Laravel uses a translation engine called blade for its view files. This makes the code you write in your views much cleaner and easier to read. As we go through this training course, we'll gradually learn more about the capabilities of blade. But for now, just remember that each view file you create needs to follow a specific naming convention:

<name-of-file>.blade.php
Enter fullscreen mode Exit fullscreen mode

Alrighty, let's get started! We're gonna create a simple file called about.blade.php. You can use the code snippet below if you want, but you don't even need to worry about putting in the original head or body tags. Blade's got you covered and will add those in for you automatically!

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        html {
            background: #f7fafc;
            box-sizing: border-box;
        }


        body {
            background: white;
            max-width: 28rem;
            margin: 50px auto;
            font-family: Calibri, Arial, sans-serif;
            padding: 2rem;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
        }


        h1, p {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>About Us</h1>
    <p>Welcome to the Laravel101 totorial</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

To make our view accessible, we need to define a route that points to it. We can do this in the web.php file, which is located in the routes directory.

Image description

Awesome, you just created your first view file! And hey, we were able to do it so easily thanks to Laravel's simple route creation. To do that, we used this handy command:

Route::view('url', 'view')
Enter fullscreen mode Exit fullscreen mode

where the first parameter is the URL that we want to use to access the view, and the second parameter is the name of the view file.
Now, if we want to write both paths of our project in a simpler way, the result will be as follows:

Image description

Pretty simple, huh? And the result is a view file that's easy to read and understand. Nicely done!
Passing data from server to views
Now we're gonna send some data from server to our views, this is very useful. let's create a sample blade files to display a list of names inside a directory like resources/views/me/friends.blade.php
To make our view accessible, we need to define a route that points to it. We can do this in the web.php file, which is located in the routes directory:

Route::get('/friends', function () {
    return view('me.friends');
});
Enter fullscreen mode Exit fullscreen mode

You might be used to writing paths like path/file, but in Laravel, it's more better in views to use path.file instead path/file. Of course, you can use whatever convention you prefer in your own code. the final output should look like this:

Image description

Alright, now let's talk about sending data to a view. This is where things start to get really cool!
To do this, we're gonna use the second parameter of the view function. With that, we can send an array of data with a specific key to the view we want.

Route::get('/friends', function () {
    $data = [
        'John', 'Mike', 'Susan', 'Jimmy', 'Kazem'
    ];
    return view('me.friends', [
        'users' => $data
    ]);
});
Enter fullscreen mode Exit fullscreen mode

Just remember, that variable name needs to be called inside the view if we want to use the data (I used "users").
Laravel has a really useful helper function called compact() that makes it easy to pass variable names to a view. This function creates an associative array with the variable names as keys and their current values as values. Then, we can just pass this array to our view and access the variables by name in our Blade file. let's do it in our example:

Route::get('/friends', function () {
    $users = [
        'John', 'Mike', 'Susan', 'Jimmy', 'Kazem'
    ];
    return view('me.friends', compact('users'));
});
Enter fullscreen mode Exit fullscreen mode

Now, to display the data in the view, we just use a simple PHP loop like the one bellow. It'll return the data as a list with the help of "echo":

<ul>
    <?php 
        foreach ($users as $user) {
            echo '<li>' . $user . '</li>';
        }
    ?>
</ul>
Enter fullscreen mode Exit fullscreen mode

But you might be wondering, if we're just using PHP in our views like this, then what's the point of Blade? 😉

Well, Blade is a translation engine that turns our PHP code into a much smoother, more readable syntax. It's got some awesome features that really make our code easier to work with. If you want to learn more about Blade syntax, you can check out the doc from here or just stick with me and I'll cover everything you need to know in this course.

Alright, let's dive into some Blade syntax! Here's the first thing you need to know: every command like if or for needs to start with an @ symbol and end with its corresponding closing tag.

For example, check out this foreach loop in blade syntax:

@foreach ($users as $user)
  <li>This is user {{ $user }}</li>
@endforeach
Enter fullscreen mode Exit fullscreen mode

In Blade, we can easily use HTML tags, but if we want to display data, we need to put it inside double curly braces {{}} like in the example above.
Now, let me show you an example of a conditional statement in Blade:

@if (count($records) === 1)
  I have one record!
@elseif (count($records) > 1)
  I have multiple records!
@else
  I haven't any records!
@endif
Enter fullscreen mode Exit fullscreen mode

Pretty cool, huh? The syntax is super clean and easy to read.
Alright, now let's go back to our user display example and rewrite the code with Blade syntax:

<ul>
    @foreach ($users as $user) 
        <li> {{ $user }} </li>
    @endforeach
</ul>
Enter fullscreen mode Exit fullscreen mode

As you see every thing works like charm!

Image description


Well, there's another thing we need to consider when sending data through routes. If we're dealing with a page that has a lot of data to display, our route files can get pretty messy!

That's why we use controllers. They help manage the process of receiving, processing, and sending data between the client and the server.

Alright, that's enough for now. Remember to practice what we've covered so far, and if you're enjoying the content, don't forget to share it with others!

I'll cover controllers in the next article, so stay tuned!

Top comments (0)