Tự học Laravel: (2) Tạo View

Last time, I followed the flow until the Laravel framework displayed the page. 
This time, I will create and display a new page (view) by myself.

SCENARIO

Create a contact page

ROUTING

Add settings for GET access to contact in routers/web.php.

// routers/web.php
 
Route::get('/', 'WelcomeController@index'); 
Route::get('contact', 'WelcomeController@contact');

CONTROLLER

Add a contact method to WelcomeController.php.

//app/Http/Controllers/WelcomeController.php
 
<?php
namespace App\Http\Controllers;
 
class WelcomeController extends Controller {
    // ...
    public function contact()  
    {
        return "contact";
    }
}

First, instead of using the view function in part (a), we just return the text. 
View http://localhost:8000/contact in a browser …

“Contact” was displayed

You can simply return the text.

Change to display the view.

//app/Http/Controllers/WelcomeController.php
 
    public function contact()
    {
         return view("contact");
    }
}

View http://localhost:8000/contact in a browser …

InvalidArgumentException
View [contact] not found.

I got an error. 
It has been said that View can not be found because it has not yet created contact.blade.php.

VIEW

Create contact.blade.php The content is just HTML.

<!-- resources/view/contact.blade.php -->
 
<!DOCTYPE HTML>
<html>
<head>
    <title>contact</title>
</head>
<body>
    <h1>contact me!</h1>
</body>
</html>

View http://localhost:8000/contact in a browser …

contact me!

You could see a new page. 
It is a success.

SUMMARY

You can do the following things.

  • Add Routing Settings
  • Add method to Controller and call View
  • Create new view and display

Leave a Reply

Your email address will not be published.

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