Full Stack Web Developer (Q1-Q2 2021)

Estimating read time ...
Edited 7th November 2021

Laravel: Installation, MVC and Routing

We're now ready to advance and delve into using the Laravel PHP framework which I have mentioned occasionally throughout all the previous chapters. The framework is extensive in capabilities and boasts multiple features for us developers to utilise, enabling us to build small or large scale enterprise applications without having to start at the absolute bare-bones stage each time.

Laravel is the most popular PHP framework, it is one of the top 50 most popular repositories on Github and the most popular repo under the ‘PHP’ language (at the time of writing). Other PHP frameworks do exist, including (but not limited to) CodeIgniter, Symfony, Zend and CakePHP but many of these have lost traction. The only two remaining popular PHP frameworks are Laravel and Symfony.

The Laravel framework integrates with and handles many of the essentials required when developing applications, and this includes (but not limited to):

  • Package Managers: Composer, NPM
  • Front-End Module Bundlers: Webpack (via Laravel Elixir)
  • Native Integration with the `.env` File
  • Web Routing
  • User Authentication
  • Requests (GET/POST, etc.)
  • Middleware (the ability to intercept in the middle of requests before returning a response)
  • Databases. Laravel provides integration with various types of databases natively, third party packages also exist to support further database software servers.
  • CLI support (via Artisan) with the ability to develop our own custom CLI commands
  • Blade templating and Sass (rather than vanilla HTML and CSS)
  • OOP and MVC principle practices, including CRUD implementations.
  • General application security, such as password hashing and salting, CSRF tokens, route throttling and much more handled by default.

Laravel provides further features in addition to all the above, however we won't be covering them all unfortunately. We’ll work towards slowly introducing some of the features and techniques before progressing further. Once we’ve covered the core Laravel aspects, you'll be capable of building applications that serve practical purposes.

Everything we have covered so far in this course will come in handy when we work with Laravel and building applications.

It’s also worth noting that Laravel also includes an extensive documentation which is a useful resource; additionally there is a large development community world-wide behind the framework, therefore you’ll be able to find a wealth of knowledge or support questions online, mainly on Stackoverflow and Laracasts (Laravel’s community).

1. Starting with Laravel

There are two ways we can start with Laravel (and essentially with any project at all for that matter) and that is to create a fresh installation or to clone an existing repository that exists. Initially the original developer must perform a fresh installation for the project in order to enable other developers to collaboratively work together.

1.1. New Laravel Project

To start a new Laravel project we must use the Command Line and ensure that our machines are setup with the necessary pre-requisites, which we should all have as a result of following this course. This would include PHP, composer, unix terminal and etc., all of which we downloaded previously.

We must first cd into the directory where we want to place our Laravel project. To keep things simple and in uniform, we’ll place this in our XAMPP’s htdocs directory. For a default Windows installation this would be ‘C:/xampp/htdocs’.

In our CLI we must enter the following to change directory (CD) to navigate there:

cd /c/xampp/htdocs

Next the following command will install a new Laravel project:

composer create-project --prefer-dist laravel/laravel:^8.0 <project_name>

The above command will use the Composer package manager and download Laravel version 8 (which is currently the latest version), along with all the dependencies/requisites necessary for a successful Laravel setup. The <project_name> must be replaced with our project’s name, in our case we’ll leave it called ‘laravel’ as we’re using this purely for experimental reasons. When we do progress onto developing our own apps, I would expect the name to be replaced with the project’s name appropriately, for example:

composer create-project --prefer-dist laravel/laravel:^8.0 autoparts

Running the above command may take a few minutes as it downloads and performs the necessary installation steps. As of Laravel 8, running the above command will also configure the entire application for the original developer on their machine, including pre-defining the .gitignore and .env files. When other users clone the same project, they must perform additional setup steps which has been documented below.

1.2. Cloning an Existing Laravel Project

Firstly to clone an existing Laravel project is no different than cloning any other git repository.

  1. Assuming you're using Github, you can visit the repo page and click the green ‘Code’ button.
  2. You will be presented with a pop-out that gives options on how you’d like to clone, e.g. via HTTPS, SSH or ‘Open with GitHub Desktop’. We’ll choose the last option to keep things simple, which is to open with GitHub Desktop. (If you completed the "SSH Keys and Git via CLI" section, you can use SSH.)
  3. Once open in GitHub Desktop, choose to have the repository cloned in ‘C:/xampp/htdocs’ (for Windows).

After the repository has been downloaded we’ll now need to switch to the CLI/Terminal via Git Bash. Change Directory (CD) into the cloned repo, which should be in ‘C:/xampp/htdocs/laravel’. To do this, run the following command:

cd /c/xampp/htdocs/laravel

Now run the following commands:

composer install; chmod -R 777 storage && chmod -R 777 bootstrap/cache; cp .env.example .env; php artisan key:generate
  • The first composer command will install all the packages/dependencies required by Laravel.
  • The second command will ensure the ‘storage’ and ‘bootstrap/cache’ directories provide full privileges for the Laravel app to write into.
  • The third command will create an .env file, duplicating the .env.example file.
  • Finally the last command will generate a unique key for the application, which will be used by our application for encrypting data.

By completing the above, we have cloned the repo and performed an installation of the Laravel project locally on our machines, ready for us to begin our development.

1.3. Testing the Laravel Setup

Let’s now test that the Laravel installation was a success. If you’re not already, ‘CD’ into the directory using the CLI, for us this should be cd laravel. Now run the following command:

php artisan --version

The above command makes use of Laravel’s Artisan command line tool, which is extremely useful and we can also build our own CLI functions, which can be invoked by manually typing the command or by using a Cron Job (i.e. scheduled task by the operating system).

The above command will simply print out the Laravel version our framework is based on. If the version number is returned, your Laravel setup was a success.

Now using your IDE (e.g. Atom or other preferred), add this ‘laravel’ directory as a new project (File > Add Project Folder).

2. Accessing Laravel in Our Browser

To serve the Laravel project locally we won’t be using XAMPP’s apache server, primarily as Laravel expects all traffic (i.e. visitors) to be served from the `/public` directory. The public directory cleverly builds an end-point which users can access via the browser whilst all of our source-code (i.e. all other files and directories) remain private on our server, this includes our database, routes, controllers, composer and NPM modules and much more. They are still working behind the scenes but users do not have access to them.

XAMPP expects all traffic to be served from the root directory by default and expects to find an index file (e.g. index.html, index.php and etc.). Laravel’s index file is actually located in the ‘/public’ directory.

When we setup our deployment servers last week, using Virtual Hosts (vhosts) we can configure the ‘DocumentRoot’ to be ‘/public’ so it’s not actually a problem when it comes to deployment in production.

Now instead of using XAMPP’s Apache, Laravel actually provides its own local development environment. Firstly ensure ‘Apache’ is not running in your XAMPP control panel (to avoid conflicts with Laravel’s environment). Next cd into the Laravel directory and run the following command:

php artisan serve

And if all goes well the development server will be started. You can access the project from your browser at http://127.0.0.1:8000 and the environment will watch for requests. To stop the server just hit CTRL + C in your terminal window. Whilst the development server is running you won’t be able to use the terminal window, so it’s advisable to open a new terminal tab/window.

3. The MVC Principle

The Model-View-Controller (MVC) principle mandates that all code should be separated in concerns. As we have done previously you would have noticed that your PHP file has HTML code embodied inside, whilst integrating with an API provider and also connecting to a database, all of which is stored in a single PHP file.

We did this to introduce PHP, to get us directly involved into the capabilities it offers and start programming. However at a more advanced level we should work to keeping all these concerns (i.e. returning the HTML view, connecting to a database, posting data to an API provider) separate. This enables us to develop large scale applications which are maintainable for the future, and in turn produce cleaner code. To write clean code however requires experience; my first few applications although functional were not at a high programming standard.

The MVC is broken down into three concepts:

  • Model – This is concerned with connecting to the database and handling application logic. (In Laravel ‘Model’ also refers to a single record in a database table.)
  • View – This is purely for returning the HTML/CSS/JS to the end-user, i.e. what the user sees, hence the term ‘view’.
  • Controller – The controller is the ‘glue’ between the Model and the View. It must intercept requests, process them, retrieve the relevant model (i.e. database records) and then return the view.

There are further advanced development standards we can adopt on top of MVC (e.g. 'Skinny controllers, fat models', repository/services and etc.), however we won’t be covering them to avoid confusion.

Now that we’ve made it this far (thank you for keeping up!), we will be covering working with the ‘Controller’ and ‘View’ of the MVC principle. We won’t be focusing on the ‘Model’ as we don’t want to dive into database integration with Laravel yet; we will cover this in the next chapter.

4. The dd() Method/Function

Before we go further, I’d like to mention that Laravel provides an extremely useful dd() function.

This is similar to native PHP’s var_dump() and die() methods and dd() works exactly in the same way, however dd actually combines both of these into a single method. Additionally the output from the dd to the browser is designed specifically for debugging. (DD stands for dump and die.)

So if you need to test a variable, string, object or for any other use, you may use dd() in your code. This should only be used for debugging and any instances should be removed before committing to a git repo. Example use in your controller could be:

public function update(Request $request) { dd($request); }

Alternatively you may use it in Blade files like so:

{{ dd('Hello World!') }}

Blade templating has been documented more further below in this section, so don’t worry if this is the first time you’re hearing of it.

5. The Task: Creating Our First Page

I’d like you to create your first page/view in Laravel. In order to accomplish this we must create a route, handle the resource using a controller and finally build the view.

5.1. Using a Controller (Processing the Request)

Let’s start by creating a new controller, let’s call it SiteController.

We can create a new controller by manually adding the file and entering the necessary class names, namespace and following the correct syntax or simply, we can use Laravel’s artisan command. Let’s opt for the latter. So using the CLI, ‘CD’ into the project directory and run the following command:

php artisan make:controller SiteController

This controller will now be created and pre-populated in the `app\Http\Controllers` directory. Open the file in your preferred IDE (e.g. Atom or other) and add the following inside the class:

public function yourName() { return view(‘your-name’); }

Replace yourName and your-name with your own name. Notice carefully how the function name is in camel case and the view is in kebab case. We must follow these conventions when developing in Laravel, as the Laravel framework is designed to work by following conventions rather than requiring additional configuration (i.e. it will assume to look for these resources based on the name, this will be more important when we work with Models).

Save the file and we’re now complete with the controller. You can see this controller is quite simple in nature (effectively a one liner), but for larger applications we may perform additional processing (e.g. check if a user is allowed to view the resource, or get data from the Model first and etc.).

You can read more in depth on Controllers at the Laravel Docs.

5.2. Routing

Now that we’ve created our controller and it is designed to return a view named after ourselves, we need to make this controller method accessible over a URL and this is where routing comes into place.

Firstly I’d like to mention there are a few types of routes we can define, which are:

  • web.php – This is where we define all our routes which are accessible over the web-browser.
  • api.php – Used for defining API routes for use by third-parties (i.e. your customers). All routes here will have the ‘/api/’ prefix and are generally called using a server/computer rather than a user’s browser. Laravel will also convert all responses into JSON.
  • console.php – This is used for defining our own CLI artisan commands.
  • channels.php – This is used for broadcasting data. We won’t be covering this and I won’t describe it further to avoid confusion.

Let’s get into it and create our first route. In your preferred IDE (e.g. Atom), open the routes\web.php file and add the following line:

Route::get(‘/your-name’, ‘App\Http\Controllers\SiteController@yourName’);

Again replace the kebab-case URL (your-name) and the camelCase method name (yourName) appropriately. You’ll notice that this is a ‘get’ route, which means that visitors can perform a ‘GET’ call to this route which browsers perform naturally unless instructed otherwise.

Now save the file and we’re now complete with defining our route.

You can read in more depth on Laravel Routing at the Laravel Docs.

5.3. The View (Blade Template)

Now the final stage is to create our view, which is the response which will be returned to the browser.

Laravel uses their own ‘blade template’ for the view and effectively this supports all of native HTML syntax, but it also includes additional features such as the ability to use PHP code before it is rendered. Whilst we can use PHP in blade, following MVC principles we should avoid placing any complex PHP in the views; instead this should be placed in our controllers (or in a service class at an advanced level).

Additionally we can add blade comments into the HTML and they will not be rendered to the end-user. Blade does also offer other features which HTML cannot offer alone, which we’ll cover in a later lesson.

Before we start working with the blade templating, it is advisable to install an extension/package for your preferred IDE to support the blade syntax as it is not supported by default (usually). You can download appropriately:

Let’s now build your view. In your `resources\views` directory create a new file called your-name.blade.php (replacing your-name with your name) and this again should be in kebab-case.

You can place your HTML code in here and it will be rendered for the route we created.

You can read in more depth on Blade Templates at the Laravel Docs.

Author(s)

Arif Ullah

Developer & CEO