# Building Web Applications From Scratch With Laravel

In this series, we'll build a web application from scratch with Laravel—a simple and elegant PHP web framework.

## What is Laravel?

Laravel is a clean and classy framework for PHP web development. Freeing you from spaghetti code, it helps you create wonderful applications, using simple, expressive syntax. Development should be a creative experience that you enjoy, not something that is painful. Enjoy the fresh air!

Laravel is a web application framework that describes itself as a “A Framework For Web Artisans”. According to its author, Taylor Otwell, Laravel strives to bring back the joy to programming by making Laravel simple, elegant, and, most importantly, well-documented.

From my experience with the framework, I would definitely agree that Laravel hits these three points dead-on:

• Simple—Laravel's functionalities are easy to understand and implement.
• Elegant—most of Laravel's functions work seamlessly with very little configuration, relying on industry-standard conventions to lessen code bloat
• Well-documented—Laravel's documentation is complete and always up-to-date. The framework creator makes it a point to update the documentation before releasing a new version, ensuring that people who are learning the framework always have the latest documentation.

## What Makes Laravel Different?

As with any PHP framework, Laravel boasts a multitude of functions that differentiates it from the rest of the pack. Here are some, which I feel are the most important (Based on http://laravel.com/docs).

### Packages

Packages are to Laravel as PEAR is to PHP.

Packages are to Laravel as PEAR is to PHP; they are add-on code that you can download and plug into your Laravel installation. Laravel comes with a command-line tool called Artisan, which makes it incredibly easy to install bundles.

We all know the importance of web security in this modern digital era. One of my favorite Laravel Packages, called Spatie adds a useful tool to Laravel that lets you define roles and permissions in your application. In essence, it lets you specify which users have access to what resources.

Other very useful Laravel packages include Laravel Mix (a webpack front-end build tool), Eloquent-Sluggable (for making slugs) and Laravel Debugbar (for debugging).

### Eloquent ORM

The Eloquent ORM is the most advanced PHP ActiveRecord implementation available.

The Eloquent ORM is, by far, one of the best ORM implementations I've used. Similar to how Doctrine ORM functions, it makes any work on database records simple and easy. It abstracts most functions that you'll have on models (i.e. CRUD operations) and provides a flexible way to add more. Additionally, the Eloquent ORM gives you the ability to define model relationships to retrieve records, based on their relationship to another record. For example, you can retrieve all related file records associated with a user by doing:

### Migrations

Database migrations are a great utility in any project's arsenal - especially for projects where multiple developers are involved—by making it easy to keep your database schema up-to-date with other team member's changes. In Laravel, migrations are built into the framework; they can be executed, via the Artisan command-line utility. Laravel's own Schema Builder functions are simple enough that anybody should be able to quickly write up a database schema change.

Here's an example that creates a users table in a database, taken from the Laravel documentation:

Migrations are defined inside a migration PHP file. These files go inside the app/database/migration folder in a Laravel project.

Typically, a migration file follows the naming convention: 2022_05_23_000000_create_users_table.php, where 2022_05_23 is the date and create_users_table the type of migration.

Running the migration above will create a users table consisting of the specified columns inside your chosen database. Each column is assigned a type using the type methods (see complete list in the official docs). To create a database migration, use the artisan utility as follows:

You can also perform more granular tasks on your table like adding or removing a column, reordering the columns, seeding data and so on.

Here's an example that adds the location column to the existing users table:

The file for this migration would follow almost the same naming convention discussed earlier. The only difference would be in the migration name, which would go like: add_location_column_to_users_table.

### Seeding

When developing an application, it's important that you test the functionality to see if the app is working as intended. Seeding allows you to populate your tables with fake data en masse, for testing purposes.

All seeders inside a project goes in the app/database/seeders directory. To generate a seeder, use the artisan utility as follows:

Here's a basic example that populates the users table with some autogenerated data, from the docs:

You can use model factories to generate large amounts of database records at a go. This basic example creates 50 posts for a user inside this database:

### Unit-Testing

As a believer in Test-Driven Development (Read for more info: The Newbie's Guide to Test-Driven Development), I love it when a framework has some sort of unit-testing utility baked in. Laravel's own beautifully integrates with PHPUnit, relying on its status as one of the industry's best PHP unit testing frameworks. To build a test, simply extend the TestCase class, like so:

To run your Laravel application's tests, let's, again, use the artisan command-line utility:

That command will run all tests, which are found within the app/tests/unit directory of your Laravel application.

## Let's Build a To-do Application With Laravel

Now that we know more about Laravel, it's time to get hands-on by building a web application with it from scratch. We'll build a to-do application that allows us to post items to the database. I'll also include the functionality to mark them once completed. When done, it will look like this:

In the process, we'll learn about the different concepts and features of Laravel like routing and controllers, as well as MySQL and of course, the Blade templating language.

With that in mind, let's dive in!

### Installing Laravel

There are different ways to install Laravel on your machine, your choice depends on your operating system. Laravel provides a detailed documentation on that.

Once you have installed PHP and Composer, creating a Laravel application becomes very straight-forward. Open your terminal and run the following command to create a brand new app inside a folder named my-app (use any name you wish):

After the application has been created, cd into my-app and start your development server:

Now we're done setting up the environment. After some time you should be able to access your Laravel development server at http://localhost:8000.

### Setting up Application

At this point, Laravel have scaffolded a working framework for you. You'll find a host of folders and files inside your root project folder. We'll not go over all of these folders, instead, we'll focus on the most important ones.

First, you have the app folder. This folder contains the Models and Controllers, amongst others. Next you have database folder which contains the migrations, factories and seeders. resources is where all the front end code will go and specifically. In here we find  the view folder, where we'll create the view of our application using Blade templates.

Finally, routes will contain all of our application routes. Inside routes/web.php, we'll define the web routes of our application. Now that we have a basic understanding of the framework, let's create and serve our first page.

By default, Laravel sets up a starter template at resources/views/welcome.blade.php, which is what we see at http://localhost:8000. This is a Blade template, not HTML. Whenever we modify that file, the changes are reflected on the browser. You can modify yours and see the changes in effect.

First, we'll bring in Bootstrap CSS to our project by embed its CDN link in the <head> tag of our  welcome.blade.php file:

Then we'll create a basic Bootstrap CSS form for our To-do layout:

### Hooking up the database (MySQL)

MySQL is a popular relational database, similar to Microsoft SQL Server and Oracle. It's used by many web applications to create relational datastores where the records relate to one another.

You can get MySQL via popular distributions like WAMPServer and XAMPP. Create a new database in your local MySQL installation and name it todo. In the following section, we'll create and migrate a table comprising of some columns to this database.

Once you have your MySQL server set up, simply open the .env file in your project root folder and pass your database name to DB_DATABASE, like so:

### Creating a Table and Adding Columns (Models and Migrations)

Earlier we learnt that migrations are simply a way to execute changes to our database tables. They allow us to create tables and add or remove columns right from our application. But in relation to databases, there is another important concept we must learn about, and that is Models.

Models allow you to retrieve, insert, and update information into your data table. Typically, each of the table in database should have a corresponding “Model” that allow us to interact with that table.

Now we'll create our first model, which is ListItem. To do so, we run the following artisan command:

The -m flag creates a migration file along with the model, and this migration file will do inside app/database/migrations folder.

Next, we'll modify the migration file and add the columns we want on our list_items table:

Here we are adding the fields: id, name and is_complete. table->timestamps() will automatically generate two fields in our database: created_at and updated_at.

Run the following to migrate the table and its columns to your database:

### Setting up Routes

In Laravel, all requests to the application are mapped to specific functions or controller by Routes. They are responsible for instructing the application where URLs go. For example, if we wanted http://localhost:8000/home to render the home view file, we can create the following route within web.php, found inside the routes folder:

Alternatively, if we instead need to route http://localhost:8000/home to a Controller, say, the HomeController.php controller, we might do something like this:

This would route to the HomeController.php controller file. Any action method there will be made available as well. To take things further, you can specify a particular method to handle that route:

Your HomeController.php file will basically look like this:

Don't worry, we'll learn more about controllers soon. Basically, what we did is specify the index method inside the HomeController class to be called when a user navigate to localhost:8000/home.

In addition, a route name, home.index, is assigned to the route. This is especially useful if you're using a templating language like Blade (as we'll see soon). Sometimes two routes may share the same path (eg. /thread), however, one is GET and the other, POST. In such case, you can distinguish both by using different route names, preventing mix-ups.

An important thing to note here is that by default, Laravel does NOT route to the controllers like other PHP-frameworks do. This is by design. By doing so, we can actually create simple pages without the need to create a controller for it. For example, if we wanted to create a static Contact Us page that just lists down contact information, we can simply do something like this:

This will route http://localhost:8000/contact-us and render the resources/views/contact-us.blade.php file. Since we don't really have any dynamic processing on this page, we can just automatically render the view file, saving us the time to create and configure a controller to do so.

There is so much more that we can do with Routes in Laravel. Stuff like:

• HTTP Verbs—Laravel gives us the ability to create routes, based on the HTTP verb that was used in the request. For example, we can have a GET request to the /home route go somewhere different from where the POST request would go.
• Wildcards—this lets us route a URL with a wildcard value attached to it (e.g. /user/(:num) where (:num) is the user's ID)
• Middlewares—these let us run some functionality before or after a route is executed, depending on the route that was called. For example, we can create an auth middleware that will be called before all routes, except the home and about routes.

For the purposes of this web application, though, we only need a two routes: the first route just shows the welcome page along with the todo list and the second route will be called when we submit a new todo item using the form.

Open up the web.php file, and add the following routes:

For the second, we set the method to post to indicate that we are handling a POST request. When this route is triggered, we want to call the saveItem method inside the TodoListController (we'll create it soon). A route name is also set. We'll use this name when making a POST request from the form.

Next we import the controller on top of the file:

Time to learn about controllers and create our very own TodoListController.

Creating Controllers

Typically, you define all of the logic for handling a route inside of a controller. Controllers in Laravel are found inside the app/Http/Controllers folder.

To create a controller we use the artisan utility. Remember that TodoListController whose method I said was going to handle to POST request to our "saveItem" route? It's time to create it.

Run the following command on your terminal:

This will create a TodoListController.php file inside the app/Http/Controllers folder. By convention, we'll want to name the file something descriptive that will also be the name of the controller class, which is why I went with that name.

In this controller class, we'll define two methods: index and saveItem

First we import two Models: Request and ListItem. Request gives us all the information about the HTTP request. ListItem is the model we created earlier for saving a to do list item inside our database.

The index method returns the welcome view and passes all the list items from the database. That way we can display them on the page if there is any.

The saveItem method is for saving a to do item to our database. Here we create a new ListItem instance. We then set its name to the name from the request payload, and set is_complete to 0 (represents false or "no"). Finally, we return the welcome page.

For this to work, all we have to do now is modify our welcome.blade.php file which is where we'll be making a request from and showing the to do list.

### More Controller Fun

#### Middlewares

There's a lot more that we can do with controllers, rather than them just being gateways to the view files. For example, remember the Middleware feature that I mentioned earlier in the routes section? Aside from being attached to specific Routes, we can also attach them to specific controllers! Simply create a __constructor method for the controller, and setup the middleware there. For example, if we need to ensure that a user is authenticated for all the methods in a controller, we can make use of our example auth middlware:

This will call the auth middleware on all actions in this controller. If we wanted to target some specific actions, we can refer to the only method, like so:

We can alternatively use the except method to implement the middleware on all actions, except a few:

Notice how expressive this code is?

We can even target a specific HTTP verb:

#### The Base Controller

Most, if not all, controllers extend the Controller. This gives us a way to define methods that will be the same for all our controllers. For example, if we need to create a logging method to log any controller request:

Any time we want to log a request, we can just call \$this->logRequest(); in any controller. If you want to learn more, this section of Laravel's documentation provides detailed information about controllers.

Now lets hook up our view to our already-implemented route and controller.

## Creating the Laravel View with the Blade Templating Engine

Laravel supports two ways to generate views for an application:

• PHP-based Views—these are views that make use of PHP as a templating language.
• Blade-based Views—these are views that make use of Laravel's built-in templating engine, called Blade.

The Blade Templating Engine is a templating framework that, similar to how the Smarty Templating Engine works, makes use of customized tags and functions to allow for better separation of presentation logic and application code.

For the sake of simplicity, we'll be utilizing the Blade Templating Engine, as opposed to the PHP-based views.

All view files that will make use of the Blade Templating Engine needs to have a .blade.php extension. This tells Laravel to use the engine on the view file.

Now, back in our welcome.blade.php file, we do two things:

1. We use forelse to loop through our todo list and show them. If there is no item (ie we have saved any item yet), we instead show No Items Saved Yet.
2. We set the route to POST to. We'll make our form to work by adding a CSRF token to it. This is a security measure you take whenever you're posting data with forms.

Replace the contents of div.container with the following markup:

Notice how we used the is_complete value of each list item to decide the color of the button and text content. We'll come to how we change it very soon.

Also, we used the route() helper function provided by Blade to define a form submit action; we simply route to saveItem (that we created earlier) when this form is submitted.

To test this out, navigate your browser to localhost:3000 to see the welcome page. Now type a to-do item in the text input and submit. The new item will be shown on the page.

Also, go to your MySQL database and check the list_items table to confirm. While you're there, you'll notice that all the items have their is_complete column set to 0. One last thing we'll do is add the functionality for marking a to do list as Completed.

If you recall, we already added the button for marking a todo item as completed in the view. Now we need to define the route. Go to your web.php and add the following:

Because we need to know which list item is being marked, we pass its id to the markItem method in the controller since all items had an id column and we passed the id to route() inside the view.

Next, we define the method in the controller:

Now refresh your page at http://localhost:8000 and mark any of the item. The button colour and text content will change.

Now that we have our main layout, let's see how to include other sections inside of it.

### @section and @yield

Sections let us inject content into the main layout from within a view. To define which part of our main layout is a section, we surround it with @section and @yield_section Blade tags.

Supposing we want to navigation section and inject into our main layout, welcome.blade.php. We create a new blade file and name it nav.blade.php in. In this file, we create a section called Navigation and define the markup for this section:

At this point, the navigation simply exists. To actually inject it inside the main layout, we use @yield.

### @yield

The @yield function is used to bring a section into layout file. To yield a section, we need to pass the correct path to that file inside the @yield function. For defining the path, the starting point is the views folder.

For example, assuming that we created nav.blade.php inside the views folder, this is how we bring it into welcome.blade.php:

### Importing Assets with @section and @yield

With @section and @yield you can also load CSS and JS files to a page. This makes it possible to organize your application's layout in the best possible manner.

To demonstrate, I'll create a third blade file and name it styles.blade.php. Inside this file, I'll bring in the stylesheet used in my app:

There is so much to learn about Blade that I don't cover. If you're interested in exploring further, be sure to check out their documentation.

## Conclusion

After reading this tutorial, we've learned:

• What Laravel is and how it's different from other PHP frameworks.
• How Laravel's Routing system works.
• How to create your first Laravel Controller.
• How to create your first Laravel View.
• How to use Laravel's Blade Templating Engine.

Laravel is truly an amazing framework. It's fast, simple, elegant and so easy to use. It absolutely merits being considered as the framework to be used for your next project.

The Laravel category on Envato Market is growing fast, too. There's a wide selection of useful scripts to help you with your projects, whether you want to build an image-sharing community, add avatar functionality, or much more.