The following content is the second chapter of my new e-book titled “Laravel: my first framework“. This writing is copyright by Maksim Surguy. Unauthorized copy and distribution of this material is prohibited.
Chapter 2. Getting started for Development with Laravel
This chapter covers
Installing Laravel with Composer
Meeting Artisan: the command line interface
Understanding structure of a Laravel application
Creating a website with Laravel
Getting started with some PHP frameworks could be a hard and painstaking process with a steep learning curve. Fortunately this is not the case with Laravel. Laravel is beginner-friendly, easy to install and configure, and even somebody who never used another framework before could get started quickly. This chapter will first give you an idea of how development with Laravel looks like in general. Then you will meet a tool underlying Laravel called “Composer” and you will learn how to install Laravel using it. You will meet Laravel’s helper tool called “Artisan” and after that you will learn in detail about Laravel application structure. Finally, you will build a complete and functional website with Laravel. While building the site you will see the following Laravel’s features in action: routing, templating, database operations, sending mail and more. Let’s get started by taking a high level look at the process of developing an application with Laravel.
This chapter assumes that you have Apache, PHP 5.3.7 or greater with MCrypt extension installed and database engine like MySQL already installed and set up.
2.5 Development overview
In the previous chapter you have learned that Laravel comes pre-configured to work out of the box. When you have Laravel installed you can get into developing your application right away. The development process for most web applications built with Laravel generally looks like this:
Configuring database, cache, mail and other settings if necessary
Creating the end points (routes) of your application
Creating the models and the database structure for the data
Creating the controllers and integrating them with the routes and the views
Creating the view templates that will make up the user-facing side of the application
Testing the application
Refining the code of the application
Don’t worry if some of these terms are not familiar to you yet, we will be giving proper attention to all of them throughout the book. In fact, you will get to meet most of these concepts in this very chapter!
A note on design patterns
While there are many specific software development methodologies such as BDD (Behavior Driven Development), TDD (Test Driven Development), DDD (Domain Driven Design) and more, this book will try to stay neutral and follow a general simplified development model as described above
Now that you are aware of how the development process of Laravel applications looks like in general, let’s get familiar with a very important tool that Laravel uses for its architecture.
2.6 Meeting Composer
Laravel framework consists of many separate components that are downloaded and put together automatically into a framework through a special tool called “Composer”. This tool could be downloaded from http://getcomposer.org/, it is the holy grail of dependency management for PHP.
In the old days to install a PHP library or a PHP framework you could just download it as a Zip archive from a website. If those PHP libraries or frameworks were to implement third-party libraries or classes, eventually it would get hard or impossible to keep track of dependencies (due to large number of components, new versions, bug fixes or patches coming out). There were a few attempts at solving the dependency management problem in PHP community in the past. Maybe such things as PEAR or PECL sound familiar to you? Those are some of the popular PHP dependency managers but due to their shortcomings they are failing at delivering the promised efficiency when it comes to publishing new dependencies or managing already existing ones inside a library or a framework. Learning from past mistakes and from other software development ecosystems, PHP community eventually came up with a tool that is flexible, powerful and easy to use – Composer.
Being a tool like “npm” for NodeJS or “RubyGems” for Ruby, Composer allows PHP developers, including those who develop with Laravel, to easily specify which other PHP libraries are used in their code or initiate installation and update of those dependencies through the command line. Composer has been around since 2011 but just like Laravel, matured very quickly into a solution that many developers love to use. Before creating your own library be sure to check Composer’s website for existing solutions because there are thousands of packages to choose from.
Making Composer as the tool of choice for installing Laravel and managing its components allows for great flexibility and extendibility of Laravel applications.
2.7 Installing Laravel
When you have Composer configured (see Appendix for instructions on that), you can install and start using Laravel by just executing one command in the command line replacing “companySite” with the name of your project:
After executing this command from the command line Composer will download all components that Laravel is comprised of and weave them together into a framework ready to become your next web application.
You will need to run this command for every new Laravel project unless you create some base template that you could use for all of your applications
2.8 Meeting Artisan: Laravel’s command line interface
Laravel comes pre-packaged with a powerful command line interface (CLI) called “Artisan”. Many repetitive tasks like model creation, running database migrations, launching development server and more can be executed with Artisan. Besides over 30 built-in commands Laravel allows for creation of custom commands.
Artisan Command Line Tool, or Artisan CLI, is a helper tool that comes with Laravel and could be used through operating system’s command line to accelerate development of a web application.
You can run Artisan commands through your system’s command line (ex. Terminal on Mac OS X). Navigate to your Laravel application’s root and run the following command:
You should see the version of the framework your application uses and a list of all commands available trough Artisan CLI. Executing commands through Artisan affects only the application that you navigated to in the command line, not all Laravel applications system-wide. You will get to use many of Artisan’s commands throughout this book to accelerate development. Now that you have learned about installation and have met the Artisan CLI, let’s take a look at the general structure of a web application built with Laravel.
2.9 Application structure overview
A web application built with Laravel consists of certain components that work together to make up a product that functions as the developer intended. Some of these components the developer will need to create: Model-View-Controller code of the application, definition of application’s endpoints (routes), database structure (migrations, models), and unit tests. Others, the developer needs to adjust and configure: various application settings, environment settings and third party packages. Figure 2.1 illustrates which components a Laravel web application consists of:
Figure 2.1 Components that make up a Laravel web application
Even though that might look like a lot of parts to an application, don’t worry, as you will see throughout this chapter not all of them need to be created or modified by you for each and every application.
All these parts of the application will need to be located in specific places inside of a folder that is created after installation of Laravel following instructions in the “Installing Laravel” section. Let’s start discovering the directory structure of a typical Laravel application by looking at the root level of the application.
2.9.1 Files and folders in the root level of the application
The root folder of Laravel application contains Composer configuration, condensed information about the framework, folders containing environment settings, public-facing files, application code and folder with all installed packages including packages that make up Laravel framework itself. Table 2.1 shows a list of all files and folders in application’s root directory when Laravel is installed through Composer’s “create-project” command:
Table 2.1 List of root-level files and folders of a Laravel application
Folder or file
Contains your application’s code
Contains Laravel framework’s directory paths, compiled Laravel framework file and application environment settings
Third party packages and packages making up Laravel are installed into this folder.
This Composer configuration file contains a list of packages that the application is using, version settings for each package and stability settings
Contains instructions on how to contribute to Laravel PHP Framework.
Provides general information about Laravel and links to documentation, pull requests and the license of the application. If you are making an open source project on top of Laravel be sure to update this file to reflect the purpose and description of your application
Laravel has a special command that launches the current application on the system’s PHP server. This file is a helper file for that functionality
Provides the built-in command line interface for Laravel,so that a developer can accelerate certain tasks
Configuration file for PHPUnit unit testing tool
There will be times when you won’t have to touch all of these files and folders during development of your application. For example “vendor” folder is managed by Composer tool so you don’t need to modify anything in that folder, you would go into “bootstrap” folder only when you want to add a new environment setting, “phpunit.xml” file will only be modified when you will be using PHPUnit unit testing tool, etc. On the other hand there is one very special folder inside of the root, it is called “app” and it will contain the actual code of your application. Let’s take a look inside of that most important folder.
2.9.2 Contents of the “app” folder
When building applications with Laravel, this folder will be the center of your attention. The routes, route filters, various configuration settings and database migrations for your application will reside in this folder. Because Laravel uses Model-View-Controller pattern for your application, you will notice “models”, “views” and “controllers” folders among other folders in the “app” folder. These folders store your application’s data models, view templates and application controllers respectively. Table below (table 2.2) shows a list of all files and folders inside of the “app” directory:
Table 2.2 Contents of the “app” directory
Folder or file
Classes that represent the data models
Templates for views and view layouts
Application-specific settings such as database credentials, session and cache driver settings
Database seeds (sample data) and database migrations
Language strings for validation, pagination and email reminders
Custom classes containing Artisan commands
Cache, temporary sessions and compiled views
Files that help you adjust an error handler and,application maintenance mode behavior
Application’s unit tests
Logic and definition of filters used in the application
List of all registered endpoints of the application (routes)
Knowing the file and folder structure of a Laravel application will help you put things in right places so please take a closer look at each file and folder created after installing Laravel.
2.9.3 Configuration settings
Configuring a Laravel application is pretty simple comparing to other frameworks or hand made code. Configuration files in a Laravel application are stored inside directory “app/config” and have file names corresponding to what settings they affect. In table 2.3 let’s explore responsibilities of each configuration settings file and folder:
Table 2.3 Configuration settings inside of the “app/config” directory
Folder or file
Contains settings for
Packages that the application is using
Application key, timezone and locale, debugger settings, service providers and aliases for classes
Authentication driver, model and table used to represent users, password reminder settings
Cache driver, cache database connection and table
Classes that will be included when application is optimized
Database connection for MySQL, Sqlite, Postgres, SQLServer and Redis
Email driver, SMTP settings, “From” address and name
Queue driver and connection
Session driver and connection, session lifetime and name of the cookie
Creation of new packages using Laravel’s Workbench tool
By default the configuration settings are set so that you can use Laravel right away:
The session driver is set to save sessions on the disk inside of “app/storage/sessions” directory.
The cache driver is set to save the cache on the disk inside of “app/storage/cache” directory.
The time zone is set to UTC.
The language is set to English.
The database driver is set to MySQL (you only need to provide connection settings).
The provided settings are enough to get started but most likely your application will use a database or have your own time zone, and some settings will have to be different than the provided defaults. The comments inside of each configuration settings file make it easy to understand what the options are for each setting. Besides the default configuration stored in “app/config” folder, Laravel uses a concept called “environments” to manage application settings depending on where the application is being accessed from – a local machine or by going to a URL on the web. We will learn about environments a bit later, but meanwhile let’s apply the knowledge we learned in this chapter to create a fully functional Laravel application, a company website!
2.10 Tutorial: building a website with Laravel
Let’s imagine that you are running a marketing/development company and you would like to build a simple website for your company. The company website will consist of three simple pages: home page with a welcome message, a page that lists all services offered by the company and a contact page with company’s contact information and a functional contact form. The sketches (wireframes) for the company website follow in figure 2.2:
Figure 2.2 A wireframe of company website’s pages
Following the development of an application from start to finish will give you an idea of how the development with Laravel looks like in practice. When you finish building the application you will be familiar with the way Laravel applications are structured and you will see how Laravel makes it easy for you to modify your applications in the future. In the process of meeting Laravel’s methods you will understand how the Laravel framework alleviates common web development problems and you will experience its advantages over plain PHP code first hand.
So that there is a concrete goal, let’s define some specifications for the site’s individual pages. These pages will have the following functionality:
Home page – a page with information about the company and a menu for navigation
Services page – contains a list of the services that the company offers, this list will be retrieved from the database and embedded into the output HTML of the page
Contact page – contains a contact form with two fields, the subject and the body of the message. This message will be sent as an HTML email to the site’s administrator by using Laravel’s mail functions.
While keeping in mind these basic requirements we will create a site that will work according to the specifications. Before we get into development let’s first take a high level look at how building a real website with Laravel looks like.
2.10.1 The big picture – development overview
The development of the company website will consist of 9 steps in the following sequence, starting with installing Laravel (figure 2.3):
Figure 2.3 Overview of the development steps necessary to build an application
Installing Laravel by creating a new Laravel project.
Configuring application settings for the DB and for sending of emails
Defining application’s endpoints (routes)
Creating the HTML templates for each of the site’s pages
Create the DB structure and the data model for the services offered by the company
Filling the DB with data that represents the services offered by the company
Connecting the HTML templates to the endpoints (routes) of the application
Adding validation to the contact form to prevent empty submissions
Adding ability to send emails from the application
At the end of the development process you will have a fully functional company website that will work according to the specifications we defined in the introduction to this section. Let’s start the development of the company site by installing Laravel!
2.10.2 Creating a new Laravel project
To download and install Laravel we will use Composer command described in section 2.3 of this chapter. Open up your command line and navigate to where you would like the company website created, then execute “create-project” command that will create a new Laravel project:
After Laravel’s components are downloaded and put together by Composer, you should see a new folder called “companySite” appear in the current directory. Navigate to the new folder, in particular switch to the “app” folder because the “app” folder will be the heart of your application. You will see a folder structure described in section 2.5.2. Open up your favorite code editor and get ready to write some code.
2.10.3 Configuring application settings
In case with our example website there are only two things to configure, database settings and email driver settings (figure 2.4):
Figure 2.4 Overview of application settings configuration
Since the application will use a database to store the data for the services that the company offers, you will need to create a database first and then tell the Laravel application what settings to use for the database connection. To change the database connection settings open up “database.php” file in the “app/config” folder and set the settings to match your database connection, for example listing 2.1 shows settings for MySQL database engine:
Listing 2.1 Adjusting MySQL database connection settings in app/config/database.php
This book will use MySQL as the database engine of choice but you are free to use any of the four database engines that Laravel supports: MySQL, Postgres, SQLite, or SQL Server.
Now that the database settings are configured let’s configure the settings for sending email. Laravel supports three different email drivers: PHP’s built in “mail” driver, “smtp” driver and the “sendmail” driver. For this tutorial we will use the “mail” driver that comes with PHP because it needs minimal setup. The mail settings for the Laravel application are located in “app/config/mail.php” file so let’s open it and edit the following lines (listing 2.2), saving the file afterwards:
Listing 2.2 Adjusting email driver settings in app/config/mail.php
That’s it! Thanks to adjusting these settings we will be able to send email through the contact form in the application. This concludes configuration of the application, the rest of the settings are set to reasonable defaults (as specified in section 2.5.3). Next up, you will be defining the routes for the application.
2.10.4 Specifying endpoints (routes) of the website
Each website and web application has certain endpoints that are reachable by typing a URL in the browser’s address bar. These endpoints are called “routes” (we will look more into the concept of routes in chapter 3). Our example website will have routes for the following URLs, along with descriptions of what they will do:
“/” – root route, will show the index page of the company site
“services” – will show the services page
“contact” – will show the contact page, also route is used to submit the contact form
In Laravel applications, the routing is defined in “app/routes.php” file. Open that file up, you should see the following default code (listing 2.3) that comes with a new Laravel application:
Listing 2.3 Initial contents of app/routes.php file
We will specify the application’s routes by replacing the default route with the following definitions for the application’s routes (listing 2.4):
Listing 2.4 Modifying routes in the app/routes.php file
Having defined these routes we can now test the application in the browser and see the routes working. Let’s start Laravel’s development server by using an Artisan command in the command line:
This command will launch system’s PHP server on port 8000 and will make the application reachable by typing the following URL in the browser:
Go ahead and try the three new routes in the browser, the root route, the services page route and the contact page route. You should see the text output according to what we specified in the “routes.php” file (figure 2.5):
Figure 2.5 The basic routes for three pages set up and displaying text when you visit them
Later in this chapter we will come back to these routes and add ability to display a template file instead of just text strings.
2.10.5 Creating the database structure and the model for the data
Next step in the development of the application will be adding application’s models and specifying the structure of the data in the database (figure 2.6):
Figure 2.6 When the routes are set up, create the database structure and data model
As we defined in the specifications, the database will be used only for one purpose – to retrieve the list of services that the company offers. Each service offered by the company will have a title and description and a list of these services will be shown on the “services” page of the site. What could the structure be for the table that will store the company’s services? Let’s think this through. First, a unique id is needed; we can use an auto-incrementing integer for that and just call it “id” for simplicity. Second, we will give the title to each service, and third, some text description. Last, let’s give this table a name “services” since that perfectly describes what data it will store. That is all we need for this simple application’s database. Please take a look at the resulting table structure in figure 2.7:
Figure 2.7 Database structure for table “services” that will store company’s services
With this database structure in mind, we could create the “services” table through various means, by using PHPMyAdmin, the command line or by using Laravel’s database migrations. What are migrations? Migrations are like blueprints for a database. Migrations allow developers to have an easy way to keep track of changes in database structure; they are very much like version control for a database structure. For the purpose of seeing more of Laravel’s capabilities, let’s use a migration to create our table with Laravel. We will use Laravel’s helper tool Artisan to create the skeleton for the migration, so go back to the command line and execute the following command (make sure you are in application’s root directory):
After the migration skeleton is created, it will appear in “app/database/migrations” folder, the file will have a name that starts with the current date/time and ends with “create_services_table.php”. Open this file in the code editor. You will need to fill the contents of the “up” and “down” functions of the migration file with the following schema definitions (listing 2.5):
Listing 2.5 Migration schema for “services” table
The migration definition has been created but to translate the above migration into a “services” table in the database you need to run the migration by executing artisan’s migrate command from the command line:
Keep in mind that the operations with the database will use the database connection settings you have provided in the database.php settings file. If those settings were set correctly you should see a success message in the terminal, something like “Migration table created successfully. Migrated: timestamp_create_services_table”. Now if you check your database you will see that Laravel created the table “services” with the fields you specified in the migration file.
To use the “services” table in the application we need to make Laravel aware of what DB tables are available for use and the way to do that is to define data models for each separate kind of data that the application will be working with. Laravel comes with a powerful Object-relational mapping called “Eloquent ORM” that makes working with the data in databases very easy. Eloquent ORM has a few conventions that we will make use of.
The first convention is that Laravel uses an auto-incrementing integer with the name “id” as the primary key for the records in tables. Although this could be easily changed if needed, this is exactly what we have already so we won’t have to modify our existing table.
Another convention is that Laravel likes your tables to be plural but the data models for the tables to be singular (this too is flexible). As an example if you have a table called “products” in the database, your model should be named “product”, if you have table called “users” your model for that table would be named “user”. For this particular application we need to create a data model that will make Eloquent ORM aware of the “services” table and the way to do that is to create a model called “Service” in the “app/models” directory, create a new file called Service.php with the contents of listing 2.6 and place it into “app/models” folder:
Listing 2.6 Data model for services offered by the company
This is all that is needed to tell Laravel about the “services” table in your database. You do not need to specify the name of the “services” table anywhere in the application. Laravel will assume that there is a table named as a plural of the class “Service” in the “app/models” folder. Now when you need to access the data from the “services” table throughout the application you will be able to use Eloquent’s powerful methods of accessing and managing data.
2.10.6 Filling the database with data
You have the “services” table structure ready but the table is empty and there is no “services” that we can show on the “services” page. You should fill the “services” table with information about the services that the company offers. This can be done in many ways. For example you can use PHPMyAdmin tool or the command line to create the rows for “services” table. But for the purpose of exposing you to Laravel’s power and might we will use one of Laravel’s tools to fill the data. Laravel has a built-in way to populate the data in the database. Populating a database is called “seeding” the database.
We will seed the database by creating a class called “ServiceTableSeeder” with a single function “run” that will simply create three different services that will be later displayed on the site. Please create “ServiceTableSeeder.php” in the “app/database/seeds” folder of the application and place the code from listing 2.7 in it:
Listing 2.7 Database seed for “services” table
After creating the seed class it needs to be executed in order for the data to appear in the database. Laravel’s DatabaseSeeder class located in “app/database/seeds” folder is the right place to call the execution of the new ServiceTableSeeder class. Let’s open up the “DatabaseSeeder.php” and add a single line to it’s run function (listing 2.8):
Listing 2.8 Contents of modified app/database/seeds/DatabaseSeeder.php file
Now that we have the seed defined and the DatabaseSeeder configured to run it, we need to execute Laravel’s seed command in the command line and it will create the data in the database:
If you see a message that says “Database seeded!” then all is well and the content you have defined in the “ServiceTableSeeder” class will be translated into the data in the “services” table. Check your database to make sure the seeding went well and if it did, let’s continue developing our application and start showing the data in the browser!
2.10.7 Creating HTML and Blade views
While we have our application’s internals mostly finished, the application so far doesn’t have any face to it. Right now all we show to the user is the blank screen with a line of text coming from the application’s routes. Let’s improve that by creating HTML templates for displaying information on each page and for presenting the navigational menu of the site. Then when we have the view templates all ready we will get routes to display these templates in the browser (figure 2.8):
Figure 2.8 Create HTML templates
Laravel comes with a simple yet powerful templating engine called “Blade”. The templates made with Blade look much like plain HTML but with sprinkles of some special statements that make it possible to output PHP data, looping over it, inject other templates, use different layouts and more. Using Blade can definitely save you time and spare from headache when it comes to creating the application’s pages and maintaining the visual aspect of the application.
Application’s view templates are located in the “app/views” directory and files that use Blade syntax end with “.blade.php” in the file name. One of the most useful features of Blade is ability to use a common layout for desired templates of the site and we will make a simple layout that all of the pages of the site will share. Let’s again look at the desired look of the company site in figure 2.9:
Figure 2.9 A wireframe of company website’s pages
184.108.40.206 Building the layout
From this approximate sketch we see that the navigational menu is common to all three pages and the content that goes below the menu is different between the pages. We will build a layout that will allow us to keep the common elements, in this case the site’s navigation in one place and the part that changes, the content, in another. Let’s create the application layout by making a new file in the “app/views” directory, call it “layout.blade.php” and the contents of it will be as follows in listing 2.9:
Listing 2.9 Blade Layout for the company website (layout.blade.php)
220.127.116.11 Building the template for the home page
We have the layout for the site ready. Now let’s create the templates that will be inserted into this layout. These templates will also go into “app/views” directory and they will be used to display content onto the page. First, let’s create the template for the home page as in listing 2.10 and place it in “home.blade.php” file:
Listing 2.10 Blade template for the home page (home.blade.php)
18.104.22.168 Building the template for the services page
As we specified before, the services page will display the data from the database so the template for this page will need a bit more explanation. One of the best practices of web development is to never do calls to the database from the view templates. Therefore we will do the database calls elsewhere and then pass the retrieved data as objects to the view template. We can then display the data using Blade’s clean and easy to read syntax. Let’s create “services.blade.php” file in the “app/views” directory and have the contents of listing 2.11 in it:
Listing 2.11 Blade template for the services page (services.blade.php)
That’s it for the services page! No messy PHP, no database calls from the view template, this looks nice and clean. Let’s build the template for the last page of the site, the contact page!
22.214.171.124 Building the template for the contact page
The contact page will feature the form that will consist of three inputs, the text input for the subject of the message, the text area for the body of the message, and the submit button. While we could hand code the HTML form, it could be faster to use some of the Laravel’s built-in methods for building the forms in the templates. As a demonstration, the complete HTML for the form page would look like listing 2.12:
Listing 2.12 HTML code of the contact page without using Blade
This is quite a bit of code. Let’s see how Laravel can make it easier for you to create a form for the contact page. Laravel provides multiple shortcuts for opening and closing forms, creating labels, text inputs, buttons, selects and much more. Using these shortcuts will make the code cleaner and easier to modify. Let’s look at this aspect of Laravel in action by creating a template, “contact.blade.php” in “app/views” folder, and by putting the following contents in it (listing 2.13):
Listing 2.13 Blade template for the contact page (contact.blade.php)
As you can see we have achieved the same HTML output with a lot less code by using Laravel’s Blade templating engine. At this point the view templates are complete and we would like to display them in the browser by adjusting our routes to show the templates instead of text strings. Let’s do that in the next section!
2.10.8 Displaying view templates from the routes
In section 2.6.4 we left the routes in a state where they are just displaying simple text strings. Of course the time of the blank pages with a single string is now over and we will connect the routes and the view templates together. For simplicity, we can use Laravel’s “View::make()” functionality to render the templates when the pages are requested in the browser.
126.96.36.199 Connecting the home page route to the view template
Let’s start with the index route, as it is the most basic one, the route for showing the site’s homepage. Since all this route is doing is showing a view template, we can call Laravel’s “View::make()” function providing it with the name of our view template and it will render the template upon request. This is how it will look like in the “app/routes.php” file after replacing the text string output (listing 2.14):
Listing 2.14 Index route modified to display template for the home page
Returning a rendered view from a route will simply display it in the browser. Now if you visit the homepage of the application in the browser you should see a page that looks similar to figure 2.10:
Figure 2.10 Content of the site’s homepage displaying from the Blade template
This looks good! Even though there is no CSS to make the pages look pretty, we have a functional home page for the site now. Two pages of the site are left to be made functional, the services page and the contact page. Let’s finish up the services page.
188.8.131.52 Connecting the services page route to the view template
As you remember the services that the company offers are stored in the database and we have even created the view template for the services page. That page expects to receive an array of objects that it can then iterate through to get the title and description of each service. We will use Eloquent ORM to retrieve all services from the database and then we will pass the result to the services template. Please look at the listing 2.15 to see how this looks like in action inside of a route and modify your existing “services” route to match this one:
Listing 2.15 Services route modified to display data from services table
With these changes the services route should now be fully functional and it should display the page containing the services that we previously inserted into the database (figure 2.11):
Figure 2.11 Content of the services page displaying the list of services from the database
This was easy, wasn’t it? In other frameworks or using PDO in plain PHP retrieving records and getting various data attributes would be a bit more involved but Laravel makes development enjoyable by providing logical methods and by forcing solid yet flexible conventions.
184.108.40.206 Connecting the contact page route to the view template
The only page left for us to be developed is the contact form and we are ready to modify the route that leads to it so that it displays the template we created earlier. Replace the existing “contact” route with this one (listing 2.16):
Listing 2.16 Modified route for the contact page
Laravel will convert the Blade template we created for the contact page into HTML along with form we crafted using the “Form” methods. Now going to the “contact” URL in the browser should show a page similar to figure 2.12:
Figure 2.12 Contact page with the form rendered from the view template
We are almost there. The form is on the contact page but what happens when we try to submit it? We will receive an error stating that the requested page is not found. That is because when the form is submitted it is POSTed to the “contact” route and currently we do not have the route definition for the POST method of “contact” route. Let’s create that. We will add one more route in the “app/routes.php” file, as in listing 2.17:
Listing 2.17 Adding a POST route for the contact page at the end of routes
Voila! Now when we submit the form on the contact page we will get a message that says “Message sent”. That is kind of a lie because we don’t send anything yet, but we are optimistic. We would like to receive the values submitted by the form and email the contact request to the administrator of the company site. One problem with that is that the values provided by the user could be empty. How can we prevent submittal of an empty form or a form with invalid values? Dear reader, enter validation!
2.10.9 Adding validation to the contact form
Validation of input tells us if the data entered by the user is valid or not valid. Applying validation to form data is very easy in Laravel. We will discuss it in detail in later chapters but for now we will do the following process to verify that the submitted form data is valid:
Gather the user’s input
Define some validation rules for the input fields
Validate the input according to the validation rules
If the data is valid, proceed doing something useful, otherwise come back to the form displaying what validation errors have occurred and also preserving user’s input
With this process flow implemented and with validation in action, the “contact” route will look like the code following in listing 2.18:
Listing 2.18 Adding validation to the form input in the “contact” route
When the validation of the input data fails, the application will redirect the user back to the contact page remembering the user’s input and also storing validation errors in the session. One small thing that we now need in our view template is to add the display of the error messages that arise when the validation does not pass. We can just display the errors in a string but another way is to loop through the errors using Laravel’s HTML helpers, open up the “contact.blade.php” template file from “app/views” folder and add this line above the form methods:
Please see the listing 2.19 to verify that it is in the right place:
Listing 2.19 Addition of the validation error messages (contact.blade.php)
Validating user’s input and showing error messages will prevent an empty form to be submitted and thus will decrease the number of empty emails the site administrator will be getting. Speaking of emails, as of right now we are not sending anything even when the user has filled the input fields properly. Why don’t we fix that right away? Let’s learn how to send emails from our application!
2.10.10 Sending HTML email with Laravel
Laravel makes sending HTML emails almost too simple. Let’s first look at how we could send an email using plain PHP using the built-in “mail” function and then we will build the same functionality using Laravel’s methods to see what benefits there are to using Laravel’s email features.
We will send the contact request email to the site admin after the validation of the contact form passes. To do that in plain PHP we could add it to the POST route of the “contact” route as follows in listing 2.20:
Listing 2.20 Sending email in the “contact” POST route using plain PHP
This is good enough but the code is pretty messy and not easy to maintain. If you need to change the content of the email, recipients, add CC and BCC to the email it will not be an easy task. Laravel alleviates these problems by separating the presentation of the email from the functional part (sending it, specifying recipients, etc). Let’s achieve the same functionality but using Laravel’s easy to read methods.
We already configured the email driver to use PHP’s built in “mail” function and specified the “from” address and name (refer to section 2.6.2 to see how we did that). Now all we need is to specify which HTML template will be used for the emails and what data it will contain. Let’s create a basic view template in “app/views/emails” and call it “contact.blade.php”, the content of it will be as follows in listing 2.21:
Listing 2.21 Template for the HTML email (contact.blade.php in app/views/emails)
This template will be sent out when the contact form is submitted and when the form input passes validation. We will use Laravel’s “Mail” functionality to send the HTML email,