Tự học Laravel: (4) Truyền biến tới views

SCENARIO

  • Pass First Name and Last Name from PagesController to About View
  • Display First Name and Last Name in About View

CONTROLLER

Modify the about method of PagesController.php as follows: 
You can pass variables to the view by passing an array to the second argument of the view function.

<?php //app/Http/Controllers/PagesController.php
 
// ...
 
class PagesController extends Controller {
    public function about()
    {
        $data = [];
        $data["first_name"] = "Luke";
        $data["last_name"] = "Skywalker";
 
        return view('pages.about', $data);        
 
        /* 
        return view('pages.about');
        */
    }
 
    // ...
}

You can also write the following using PHP’s compact function

  • The compact function generates an array from local variables.
  • It seems that this application has a wide range of applications.
<?php //app/Http/controllers/PagesController.php
namespace AppHttpControllers;
 
// ...
 
class PagesController extends Controller {
    public function about()
    {
        $first_name = "Luke";
        $last_name = "Skywalker";
 
        return view('pages.about', compact('first_name', 'last_name'));        
    }
 
    // ...
}

VIEW

Modify about.blade.php to display the variables passed from the controller. 
First, let’s display variables using PHP tags.

<!-- resources/views/pages/about.blade.php -->
 
...
 
<body>
    <h1>About Me: <?= $first_name ?> <?= $last_name ?></h1>
</body>

Go to http://localhost: 8000/about and check the display. 
If “About Me: Luke Skywalker” is displayed, it is a success. 
You can see that the variables passed from the controller were available.

BLADE TEMPLATE

Next, let’s display the variables using the form of blade, which is the template engine of Laravel. 
Modify about.blade.php as follows:

<!-- resources/views/pages/about.blade.php -->
 
...
 
<body>
    <h1>About Me: {{ $first_name }} {{ $last_name }}</h1>
</body>

In blade, when displaying results evaluated by PHP, enclose in double curly {{}}. 
By the way, comments on blade are {{-- chú thích --}}described as:

Go to http://localhost:8000/about and check the display. 
If “About Me: Luke Skywalker” is displayed, it is a success.

SUMMARY

You can do the following things.

  • Pass a variable from Controller to View
  • Display variables in View
  • Use Blade’s Double Curly

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.