Hands-On Full Stack Web Development with Angular 6 and Laravel 5 - Fernando Monteiro - E-Book

Hands-On Full Stack Web Development with Angular 6 and Laravel 5 E-Book

Fernando Monteiro

0,0
40,81 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build modern, fast, and progressive web applications using modern features of PHP 7 and TypeScript




Key Features



  • Explore the latest features of Angular and Laravel to build applications that are powerful, consistent, and maintainable


  • Develop modern user interfaces with a reusable component-based architecture using Angular 6 and Bootstrap 4


  • Learn how to build secure backend APIs with Laravel



Book Description



Angular, considered as one of the most popular and powerful frontend frameworks, has undergone a major overhaul to embrace emerging web technologies so that developers can build cutting-edge web applications.






This book gives you practical knowledge of building modern full-stack web apps from scratch using Angular with a Laravel Restful back end.






The book begins with a thorough introduction to Laravel and Angular and its core concepts like custom errors messages, components, routers, and Angular-cli, with each concept being explained first, and then put into practice in the case-study project.






With the basics covered, you will learn how sophisticated UI features can be added using NgBootstrao and a component-based architecture. You will learn to extend and customize variables from Bootstrap CSS framework.






You will learn how to create secure web application with Angular and Laravel using token based authentication. Finally, you will learn all about progressive web applications and build and deploy a complete fullstack application using Docker and Docker-compose.






By the end of this book, you'll gain a solid understanding of Angular 6 and how it interacts with a Laravel 5.x backend





What you will learn



  • Explore the core features of Angular 6 to create sophisticated user interfaces


  • Use Laravel 5 to its full extent to create a versatile backend layer based on RESTful APIs


  • Configure a web application in order to accept user-defined data and persist it into the database using server-side APIs


  • Build an off-line-first application using service-worker and manifest file


  • Deal with token based authentication on single page application (SPA).


  • Secure your application against threats and vulnerabilities in a time efficient way


  • Deploy using Docker and Docker-compose





Who this book is for



This book targets developers who are new to Angular, Laravel, or both, and are seeking a practical, best-practice approach to development with these technologies. They must have some knowledge of HTML, CSS and JavaScript. Familiarity of PHP is assumed to get the most from this book.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 321

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On Full Stack Web Development with Angular 6 and Laravel 5 

 

 

 

 

 

Become fluent in both frontend and backend web development with Docker, Angular and Laravel

 

 

 

 

 

 

 

 

 

 

Fernando Monteiro

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Hands-On Full Stack Web Development with Angular 6 and Laravel 5

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Kunal ChaudhariAcquisition Editor:Larissa PintoContent Development Editor:Aishwarya GawankarTechnical Editor: Leena PatilCopy Editor: Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Aishwarya GangawaneGraphics:Jason MonteiroProduction Coordinator: Nilesh Mohite

First published: July 2018

Production reference: 1300718

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-391-2

www.packtpub.com

Eu dedico este livro a minha mãe Paschoalina Patrizzi da Silva, que luta contra o mau de Parkinson's e a Polineuropatia - durante os últimos anos e nunca perdeu o brilho no olhar de esperar por dias melhores e lutar a todo instante contra todos os efeitos colaterais das medicações e limitações impostas por essas terríveis doenças.

Mãe, você me inspira todos os dias da minha vida.

Do fundo do meu coração, muito obrigado,... Sou o que sou graças a você.

The previous paragraphs are to thank and honor my dear mother, who fights against Parkinson's disease and polyneuropathy. It was written in Portuguese so she can read and understand.

In addition, I thank my family for all support and understanding.

  
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Fernando Monteiro is a full-stack engineer, speaker, and open source contributor. He has built and made some of his personal projects open source, such as Responsive Boilerplate, Frontend Boilerplate, Angm-Generator, and TrelloMetrics, written in Angular, and Node.js. With around 16 years of experience in information technology and software development, his current focus is on web and hybrid mobile enterprise JavaScript applications.

He began his career as a graphic designer and worked in the music industry for many years, performing creation and layout work for several record labels around the world such as; Nuclear Blast, Century Media, Listenable Rec, Hellion Records, and many others.

In addition, Fernando is a packt pub author, since 2013, and has published the following books - Instant HTML5 Responsive Table Design, Learning Single-page Web Application Development, AngularJS Directives Cookbook, Node.JS 6.x Blueprints, and Node.JS Projects. When not programming, he enjoys riding motorcycles, making his own beer, and watching movies with his family.

 

 

About the reviewer

Sonny Recio is experienced developer with a five-year track record of commended performance in modular and object-oriented programming. He is well-versed in all phases of the software development life cycle, with a strong working knowledge of algorithms and data structures. 

He gained five years of solid experience in C# and .NET/ASP.NET, along with writing web APIs and JavaScript in different industries.

You can find him on Twitter (YellowFlashDev), Instagram (yellowflashdev), GitHub (reciosonny).

 

I would like to personally thank my family, my loved ones, and my closest friends who pushed me further, and for their continued support throughout my career. Above all, I would like to thank God for everything I have. Without them, my accomplishments wouldn't have been possible.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Hands-On Full Stack Web Development with Angular 6 and Laravel 5

Dedication

PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Understanding the Core Concepts of Laravel 5

Setting up the environment

Installing Composer package manager

Installing Docker

Configuring PHPDocker.io

Setting up PHPDocker and Laravel

Installing VS Code text editor

The basic architecture of Laravel applications

Laravel directory structure

The MVC flow

Laravel application life cycle

Artisan command-line interface

MVC and routes

Creating models

Creating controllers

Creating views

Creating routes

Connecting with a database

Setting up the database inside a Docker container

Creating a migrations file and database seed

Using the resource flag to create CRUD methods

Creating the Blade template engine

Summary

The Benefits of TypeScript

Installing TypeScript

Creating a TypeScript project

Benefits of TypeScript

Writing JavaScript code with static types

Creating a tuple

Using the void type

The opt-out type checking - any

Using enum

Using the never type

Types: undefined and null

Understanding interfaces, classes, and generics in TypeScript

Creating a class

Declaring an interface

Creating generic functions

Working with modules

Using the class export feature

Importing and using external classes 

Summary

Understanding the Core Concepts of Angular 6

Angular 6 – smaller, faster, and easier

Angular and the component method for developing modern web applications

Angular's main building blocks

The component life cycle

Installing the tools – Git, the Angular CLI, and VS Code plugins

Installing Git

Installing the Angular CLI

Installing VS Code Angular plugins

Creating a simple Angular application

The structure of an Angular application

 The package.json file 

Dotfiles – .editorconfig, .gitignore, and .angular-cli.json

Environments

Running the sample application

Adding a new module

Adding a new component

Adding a new route 

Creating an Angular service

Template data binding 

Simple deployment

Summary

Building the Baseline Backend Application

Additional notes about Laravel with Docker

Creating the Docker Compose foundation

Configuring nginx

Configuring php-fpm

Creating a docker-compose configuration file

Building the application container

Using PHP Composer to scaffold a Laravel application

Creating the application scaffold

Running the application

Setting up a MySQL database

Adding a storage folder

Configuring the .env file

Using a MySQL external client

Migrations and database seed

Creating the migration boilerplate

Creating our first database seed

Exploring the Workbench table view

API documentation with the Swagger framework

Installing the L5-Swagger library

Creating the application API controller

Generating and publishing the API documentation

Adding Swagger definitions

Summary

Creating a RESTful API Using Laravel - Part 1

Preparing the application and understanding what we are building

Refactoring the application files

What we are building

The application's summary

Creating models and migrations files

Adding content to migration files

Eloquent ORM relationship

One-to-one relationship

One-to-many relationship

Many-to-many relationship

Seeding our database

Querying the database using Tinker

Creating controllers and routes

Creating and updating the controller function

Creating the API routes

Generating Swagger UI documentation

Summary

Creating a RESTful API Using Laravel - Part 2

Dealing with request validation and error messages

HTTP status code

Implementing the Controllers validation

Adding custom error handling

Checking API URLs with the Swagger UI 

Get all records

Get record by ID

Checking API response errors

Token-based authentication

Installing tymon-jwt-auth

Updating the User model

Setting up the auth guard

Creating the authController

Creating user routes

Protecting API routes

Creating and logging in a User

Dealing with Laravel resources

Creating BikesResource

Creating BuildersResource

Creating ItemsResource

Creating ratingResource

Adding resources to controllers

Summary

Progressive Web Applications with the Angular CLI

Starting a web application with the Angular CLI

Preparing the baseline code

Scaffolding a web application with the Angular CLI

Creating the directory structure

Building the baseline for a PWA

Adding PWA features using ng add

Understanding the key files in PWA

PWA in action

Running the application in production mode

Angular service – workers in action

Debugging a progressive web application

Creating boilerplate Angular components

Creating the home module and component

Creating the bikes module and component

Creating the builders module and component

Preparing Auth routes – login, register, and logout components

Creating a layout component

Summary

Dealing with the Angular Router and Components

Preparing the baseline code

Adding components to our application

Dealing with Angular routes

Creating authentication routes

Creating home routing

Configuring child routes for details pages

Adding builders child routes

Adding bikers child routes

Refactoring app.component.html

Building frontend views

Creating the navigation component

Creating the home view and template

Creating the bikes router-outlet

Creating the bike-list view and template

Creating the bike-detail view and template

Creating the builders router-outlet

Creating the builder-list view and template

Creating the builder-detail view and template

Creating the login view and template

Creating the register view and template

Testing routes and views 

Summary

Creating Services and User Authentication

Preparing the baseline code

Dealing with models and classes

Creating the User class model

Creating the builders class model

Creating the Bike class model

Using the new HttpClient to deal with XHR requests

Creating the auth service

Creating the Register function

Creating the Login function

Creating the Logout function

Creating the setToken and getToken functions

Creating the getUser function

Creating the isAuthenticated function

Creating the handleError function

Creating the bikes service

Creating CRUD functions

Creating the voteOnBike function

Creating the handleError function

Creating the builders service

Dealing with the HttpErrorHandler service

Creating a handler error service

Importing HttpErrorHandler into app.module.ts

Refactoring the builders service

Refactoring the bikes service

How to use authorization headers

Creating an HTTP interceptor

Adding AppHttpInterceptorService to the main module

How to protect application routes with route guards

Creating the route guard for bike-detail

Summary

Frontend Views with Bootstrap 4 and NgBootstrap

Preparing the baseline code

Installing the Bootstrap CSS framework

Removing the Bootstrap CSS import

Adding Bootstrap SCSS imports

Overriding Bootstrap variables

Writing Angular templates with Bootstrap

Adding template bindings to the navigation component

Adding template bindings to the login page

Adding template bindings to the register page

Adding template bindings to the bike-detail page

Adding template bindings to the bike-list page

Adding template bindings to the builder-detail page

Adding template bindings to the builder-list page

Setting up CORS on a Laravel backend

Setting up Laravel CORS

Connecting Angular services with application components

Adding environment configuration

Creating the navigation methods

Creating the bike-detail methods

Creating the bike-list methods

Creating the builder-detail methods

Creating the builder-list methods

Dealing with Angular pipes, forms, and validation

Creating a pipe filter

Intoducing Angular forms

Understanding Angular template-driven forms

Reviewing the login form template and component

Understanding Angular reactive/model-driven forms

Reviewing the register form template and component

Adding frontend form validation

Dealing with form validation on template-driven forms

Dealing with form validation on model-driven forms

Summary

Building and Deploying Angular Tests

Preparing the baseline code

Setting application linters

Adding stylelint for SCSS files

Adding new scripts to the package.json file

Adding the .stylelintrc configuration

Installing the Stylelint plugin for VS Code

Setting VS Code for the new linter

Applying stylelint rules on style.scss

Fixing SCSS errors

Adding TSLint-angular to the package.json file

Creating linter tasks in package.json

Understanding Angular tests

Writing unit and e2e tests

Fixing unit tests

Fixing authGuard tests

Fixing authService tests

Fixing login tests

Fixing register tests

Fixing bike service tests

Fixing bike-detail tests

Fixing bike-list tests

Fixing bike tests

Fixing builders service tests

Fixing builder-detail tests

Fixing builder-list components

Fixing builders tests

Fixing home tests

Fixing app tests

Fixing app interceptor tests

Adding unit tests

Fixing e2e tests

Application deployment

Creating Docker images for frontend applications

Creating a Dockerfile

Creating an nginx file

Creating npm building tasks

Creating the bash script

Running npm build scripts

Reviewing Docker commands

Building the application for production

Testing Docker images

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Web Development has come a long way since its inception. Today we want web applications that are fast, robust, and engaging, and Progressive Web Applications (PWA) is the way to go ahead. In this book we are going to build powerful web applications using two of the most popular frameworks at our disposal, Angular and Laravel.

Angular is one of the most popular frontend JavaScript frameworks for creating modern and fast PWA. In addition to being very versatile and complete, Angular also includes the Angular CLI tool for generating modules, components, services, and many more utilities. On the other hand we have Laravel framework, a powerful tool for the development of web applications which explores the use of the paradigm convention over configuration.

This book gives you a practical knowledge of building modern full-stack web apps from scratch using Angular with a Laravel RESTful backend. It takes you through the most important technical facets of developing with these two frameworks and demonstrates how to put those skills into practice.  

Who this book is for

This book is for developers who are new to Angular and Laravel. Knowledge of HTML, CSS, and scripting languages such as JavaScript and PHP is required.

The book's content covers all of the phases of the software engineering life cycle by looking at modern tools and techniques, including – but not limited to – RESTful APIs, token-based authentication, database configurations, and Docker containers and images.

What this book covers

Chapter 1, Understanding the Core Concepts of Laravel 5, introduces the Laravel framework as a powerful tool for the development of web applications and explores the use of the paradigm convention over configuration. We will see how, out of the box, Laravel has all of the features that we need to build modern web applications, token-based authentication, routes, resources, and more. Also, we will find out why the Laravel framework is one of the most popular PHP frameworks for developing web applications today. We will learn how to set up the environment, look at the Laravel application lifecycle, and see how to use the Artisan CLI.

Chapter 2, The Benefits of TypeScript, looks at how TypeScript enables you to write consistent JavaScript code. We examine the features that it includes, such as static typing and other features that are very common in object-oriented languages. Also, we look at using the new features of the latest version of ECMAScript, and find out TypeScript helps us to write clean and well-organized code. In this chapter, we will see the benefits of TypeScript over traditional JavaScript, discover how to use static typing, and understand how to use Interfaces, Classes, and Generics, as well as Import and Export classes.

Chapter 3, Understanding the Core Concepts of Angular 6, dives into Angular, which is one of the most popular frameworks for the development of frontend web applications. In addition to being very versatile and complete, Angular also includes the Angular CLI tool for generating modules, components, services, and many more utilities. In this chapter, we will learn how to use the new version of the Angular CLI, understand the core concepts of Angular, and get to grips with the component lifecycle.

Chapter 4, Building the Baseline Backend Application, is where we will start building the sample application. In this chapter, we are going to create a Laravel application using the RESTful architecture. We will take a closer look at some points that we mentioned briefly in the first chapter, such as the use of Docker containers to configure our environment and also how to keep our database populated. we will even check out how to use the MySQL Docker container, how to use migrations and database seed, and also how to create consistent documentation with Swagger UI.

Chapter 5, Creating a RESTful API Using Laravel - Part 1, will introduce RESTful APIs. You will learn how to build a RESTful API using the core elements of the Laravel framework—controllers, routes, and eloquent Object Relational Mapping (ORM). We also show some basic wireframes for the application we are building. In addition, we will look more closely at some relationships that you will need to be familiar with, such as one-to-one, one-to-many, and many-to-many.

Chapter 6, Creating a RESTful API Using Laravel - Part 2, continues our project of building a sample API, though, at that point, we will still have a long way to go in Laravel. We will learn how to use some features that are very common among web applications, such as token-based authentication, request validation, and custom error messages; we will also see how to use Laravel resources. Also, we will see how to use the Swagger documentation to test our API.

Chapter 7, Progressive Web Applications with Angular CLI, covers the changes that have affected angular-cli.json since the previous Angular version. The angular-cli.json file has now improved its support for multiple applications. We will see how to use the ng add a command to create a PWA and how we can organize our project structure to leave a single basis for a scalable project. Also, we will see how to use the Angular CLI to create service-work and manifest files.

Chapter 8, Dealing with Angular Router and Components, is where we come to one of the most important parts of Single-Page Applications (SPAs), which is the use of routes. Luckily, the Angular framework provides a powerful tool for dealing with application routing: the @angular/router dependency. In this chapter, we will learn how to use some of these features, such as router outlets and child-views, and we will see how to create master-detail pages. Also, we will start to create the frontend views.

Chapter 9, Creating Services and User Authentication, is one where we will create many new things, and we will be performing some refactoring to memorize import details. This is a great way to learn new things in a regular and progressive way. Also, we will dig deeper into the operation and use of the HTTP module of the Angular framework, now known as httpClient. In addition, we will look at interceptors, handling errors, using authorization headers, and how to protect application routes using route guards.

Chapter 10, Frontend Views with Bootstrap 4 and NgBootstrap, explains how to include the Bootstrap CSS framework and NgBootstrap components inside a running Angular application using the new ng add command from Angular CLI. Also, we will see how to connect our Angular services with components and how to use the backend API to put it all together. We will learn to configure CORS on our backend API, and how to use it with our Angular client-side application. We will also learn to deal with the Angular pipe, template-driven forms, model-driven forms, and form validations.

Chapter 11, Building and Deploying Angular Tests, covers how to install, customize, and extend the Bootstrap CSS framework, as well as how to use NgBootstrap components and how to connect Angular services with components and UI interfaces. We will learn to write Angular unit tests, configure application linters (for SCSS and Tslint) to maintain code consistency, create NPM scripts, and also create a Docker image and deploy the application.

To get the most out of this book

Some knowledge of the command line, Docker, and MySQL would be very helpful; however, it is not fully required, as all commands and examples are accompanied by brief instructions.

You need to have the following tools installed on your machine:

Node.js and NPM

Docker

A code editor—we recommend that you use Visual Studio Code

Git source control is recommend but not required

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Full-Stack-Web-Development-with-Angular-6-and-Laravel-5. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here https://www.packtpub.com/sites/default/files/downloads/HandsOnFullStackWebDevelopmentwithAngular6andLaravel5_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here 

is an example: "All PHP projects that use Composer have a file called composer.json at the root project."

A block of code is set as follows:

{ "require": { "laravel/framework": "5.*.*", }}

Any command-line input or output is written as follows:

composer create-project --prefer-dist laravel/laravel chapter-01

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "

"Search for the chapter-01 folder, and click Open."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Understanding the Core Concepts of Laravel 5

As the title of this chapter suggests, we will be providing a general overview of the Laravel framework, covering the main concepts related to the development of web applications using a web services architecture. More precisely, we will use a RESTful architecture in this book.

We assume that you already have a basic understanding of the RESTful architecture and how web services (here, we call them Application Programming Interface (API) endpoints) work.

However, if you are new in this concept, don't worry. We will help you get started.

The Laravel framework will be a helpful tool because with it, all of the data inside our controllers will be converted to the JSON format, by default.

The Laravel framework is a powerful tool for the development of web applications, using the paradigm convention over configuration. Out of the box, Laravel has all of the features that we need to build modern web applications, using the Model View Controller (MVC). Also, the Laravel framework is one of the most popular PHP frameworks for developing web applications today.

From now until the end of this book, we will refer to the Laravel framework simply as Laravel.

The Laravel ecosystem is absolutely incredible. Tools such as Homestead, Valet, Lumen, and Spark further enrich the experience of web software development using PHP.

There are many ways to start developing web applications using Laravel, meaning that there are many ways to configure your local environment or your production server. This chapter does not favor any specific way; we understand that each developer has his or her own preferences, acquired over time.

Regardless of your preferences for tools, servers, virtual machines, databases, and so on, we will focus on the main concepts, and we will not assume that a certain way is right or wrong. This first chapter is just to illustrate the main concepts and the actions that need to be performed.

Keep in mind that regardless of the methods you choose (using Homestead, WAMP, MAMP, or Docker), Laravel has some dependencies (or server requirements) that are extremely necessary for the development of web applications.

You can find more useful information in the official Laravel documentation at https://laravel.com/docs/5.6.

In this chapter, we will cover the following points:

Setting up the environment

The basic architecture of a Laravel application

The Laravel application life cycle

Artisan CLI

MVC and routes

Connecting with the database

Setting up the environment

Remember, no matter how you have configured your environment to develop web applications with PHP and Laravel, keep the main server requirements in mind, and you will be able to follow the examples in this chapter.

It is important to note that some operating systems do not have PHP installed. As this is the case with Windows machines, here are some alternatives for you to create your development environment:

HOMESTEAD

(recommended by Laravel documentation)

https://laravel.com/docs/5.6/homestead

MAMP: 

https://www.mamp.info/en/

XAMPP: 

https://www.apachefriends.org/index.html

WAMP SERVER

(only for Windows OS)

http://www.wampserver.com/en/

PHPDOCKER: 

https://www.docker.com/what-docker

Installing Composer package manager

Laravel uses Composer, a dependency manager for PHP, very similar to Node Package Manager(NPM) for Node.js projects, PIP for Python, and Bundler for Ruby. Let's see what the official documentation says about it: 

"A Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you."

So, let's install Composer, as follows:

Go to https://getcomposer.org/download/ and follow the instructions for your platform.

You can get more information at https://getcomposer.org/doc/00-intro.md.

Note that you can install Composer on your machine locally or globally; don't worry about it right now. Choose what is easiest for you.

All PHP projects that use Composer have a file called composer.json at the root project, which looks similar to the following:

{ "require": { "laravel/framework": "5.*.*", }}

This is also very similar to the package.json file on Node.js and Angular applications, as we will see later in this book.

Here's a helpful link about the basic commands: https://getcomposer.org/doc/01-basic-usage.md

Installing Docker

We will use Docker in this chapter. Even though the official documentation of Laravel suggests the use of Homestead with virtual machines and Vagrant, we chose to use Docker because it's fast and easy to start, and our main focus is on Laravel's core concepts.

You can find more information about Docker at https://www.docker.com/what-docker.

As the Docker documentation states:

Docker is the company driving the container movement and the only container platform provider to address every application across the hybrid cloud. Today’s businesses are under pressure to digitally transform, but are constrained by existing applications and infrastructure while rationalizing an increasingly diverse portfolio of clouds, datacenters, and application architectures. Docker enables true independence between applications and infrastructure and developers and IT ops to unlock their potential and creates a model for better collaboration and innovation.

Let's install Docker, as follows:

Go to 

https://docs.docker.com/install/

.

Choose your platform and follow the installation steps.

If you have any trouble, check the getting started link at 

https://docs.docker.com/get-started/

.

As we are using Docker containers and images to start our application and won't get into how Docker works behind the scenes, here is a short list of some Docker commands:

Command

:

Description

:

docker ps

Show running containers

docker ps -a

Show all containers

docker start

Start a container

docker stop

Stop a container

docker-compose up -d

Start containers in background

docker-compose stop

Stop all containers on

docker-compose.yml

file

docker-compose start

Start all containers on

docker-compose.yml

file

docker-compose kill

Kill all containers on

docker-compose.yml

file

docker-compose logs

Log all containers on

docker-compose.yml

file

 

You can check the whole list of Docker commands at https://docs.docker.com/engine/reference/commandline/docker/. And Docker-compose commands at https://docs.docker.com/compose/reference/overview/#command-options-overview-and-help.

Configuring PHPDocker.io

PHPDocker.io is a simple tool that helps us to build PHP applications using the Docker/Container concept with Compose. It's very easy to understand and use; so, let's look at what we need to do:

Go to 

https://phpdocker.io/

.

Click on the

Generator

link.

Fill out the information, as in the following screenshot.

Click on the 

Generate

project archive

button and save the folder:

PHPDocker interface

The database configuration is as per the following screenshot:

Database configuration
Note that we are using the latest version of the MYSQL database in the preceding configuration, but you can choose whatever version you prefer. In the following examples, the database version will not matter.

Setting up PHPDocker and Laravel

Now that we have filled in the previous information and downloaded the file for our machine, let's begin setting up our application so as to delve deeper into the directory structure of a Laravel application.

Execute the following steps:

Open 

bash/Terminal/cmd

.

Go to

Users/yourname

on Mac and Linux, or

C:/

on Windows.

Open your Terminal inside the folder and type the following command:

composer create-project --prefer-dist laravel/laravel chapter-01

At the end of your Terminal window, you will see the following result:

Writing lock file

Generating autoload files

> Illuminate\Foundation\ComposerScripts::postUpdate

> php artisan optimize

Generating optimized class loaderphp artisan key:generate

In the Terminal window, type:

cd chapter-01 && ls

The results will be as follows:

Terminal window output

Congratulations! You have your first Laravel application, built with the Composer package manager. 

Now, it's time to join our application with the file downloaded from PHPDocker (our PHP/MySQL Docker screenshot). To do so, follow the next steps.

Grab the downloaded archive, 

hands-on-full-stack-web-development-with-angular-6-and-laravel-5.zip

, and unzip it.

Copy all of the folder content (a 

phpdocker

 folder and a file, 

docker-compose.yml

).

Open the 

chapter-01

folder and paste the content.

Now, inside the chapter-01 folder, we will see the following files:

chapter-01 folder structure

Let's check to make sure that everything will go well with our configuration.

Open your Terminal window and type the following command:

docker-compose up -d

It's important to remember that at this point, you need to have Docker up and running on your machine. If you are completely new to how to run Docker on your machine, you can find more information at https://github.com/docker/labs/tree/master/beginner/.

Note that this command may take more time to create and build all of the containers. The results will be as follows:

Docker containers up and running

The preceding screenshot indicates that we have started all containers successfully: memcached, webserver (Nginx), mysql, and php-fpm.

Open your browser and type http://localhost:8081; you should see the welcome page for Laravel.

At this point, it is time to open our sample project in a text editor and check all of the Laravel folders and files. You can choose the editor that you are used to, or, if you prefer, you can use the editor that we will describe in the next section.

Installing VS Code text editor

For this chapter, and throughout the book, we will be using Visual Studio Code (VS Code), a free and highly configurable multiplatform text editor. It is also very useful for working with projects in Angular and TypeScript.

Install VS Code as follows:

Go to the download page and choose your platform at 

https://code.visualstudio.com/Download

.

Follow the installation steps for your platform.

VS Code has a vibrant community with tons of extensions. You can research and find extensions at https://marketplace.visualstudio.com/VSCode. In the next chapters, we will install and use some of them.

For now, just install VS Code icons from https://marketplace.visualstudio.com/items?itemName=robertohuertasm.vscode-icons.

The basic architecture of Laravel applications

As mentioned previously, Laravel is an MVC framework for the development of modern web applications. It is a software architecture standard that separates the representation of information from users' interaction with it. The architectural standard that it has adopted is not so new; it has been around since the mid-1970s. It remains current, and a number of frameworks still use it today.

You can read more about the MVC pattern at https://en.wikipedia.org/wiki/Model-view-controller.

Laravel directory structure

Now, let's look at how this pattern is implemented within an application with Laravel:

Open the VS Code editor.

If this is the first time you are opening VS Code, click on the top menu and navigate to F

ile | Open.

Search for the

chapter-01

folder, and click

O

pen

.

Expand the

app

folder at the left-hand side of VS Code.

The application files are as follows:

Laravel root folder
The phpdocker folder and docker-compose.yml files are not part of the Laravel framework; we added these files manually, earlier in this chapter.

The MVC flow

In a very basic MVC workflow, when a user interacts with our application, the steps in the following screenshot are performed. Imagine a simple web application about books, with a search input field. When the user types a book name and presses Enter, the following flow cycle will occur:

MVC flow

The MVC is represented by the following folders and files:

MVC Architecture

Application Path

File

Model

app/

User.php

View

resources/views

welcome.blade.php

Controller

app/Http/Controllers

Auth/AuthController.php

Auth/PasswordController.php

 

Note that the application models are at the root of the app folder, and the application already has at least one file for MVC implementation.

Also note that the app folder contains all of the core files for our application. The other folders have very intuitive names, such as the following:

Bootstrap

Cache, autoload, and bootstrap applications

Config

Application's configuration

Database

Factory, migrations, and seeds

Public

JavaScript, CSS, fonts, and images

Resource

Views, SASS/LESS, and localization

Storage

This folder has separated apps, frameworks, and logs

Tests

Unit tests using PHPunit

Vendor

Composer dependencies

 

Now, let's see how things work in the Laravel structure.