Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On Full Stack Web Development with Angular 6 and Laravel 5
Hands-On Full Stack Web Development with Angular 6 and Laravel 5

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

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

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

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:

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:

  1. Go to https://docs.docker.com/install/.
  2. Choose your platform and follow the installation steps.
  3. 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

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:

  1. Go to https://phpdocker.io/.
  2. Click on the Generator link.
  3. Fill out the information, as in the following screenshot.
  4. 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:

  1. Open bash/Terminal/cmd.
  2. Go to Users/yourname on Mac and Linux, or C:/ on Windows.
  1. 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 loader
php artisan key:generate
  1. 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.

  1. Grab the downloaded archive, hands-on-full-stack-web-development-with-angular-6-and-laravel-5.zip, and unzip it.
  2. Copy all of the folder content (a phpdocker folder and a file, docker-compose.yml).
  3. 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.

  1. 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/.
  1. 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:

  1. Go to the download page and choose your platform at https://code.visualstudio.com/Download.
  2. 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:

  1. Open the VS Code editor.
  2. If this is the first time you are opening VS Code, click on the top menu and navigate to File | Open.
  3. Search for the chapter-01 folder, and click Open.
  4. 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.

Laravel application life cycle

In a Laravel application, the flow is almost the same as in the previous example, but a little more complex. When the user triggers an event in a browser, the request arrives on a web server (Apache/Nginx), where we have our web application running. So, the server redirects the request into public/index.php, the starting point for the entire framework. In the bootstrap folder, the autoloader.php is started and loads all of the files generated by the composer retrieving an instance to the Laravel application.

Let's look at the following screenshot:

Laravel application cycle

The diagram is complex enough for our first chapter, so we will not get into all of the steps performed by the user's request. Instead, we will go on to another very important feature that is a main concept in Laravel: the Artisan command-line interface (CLI).

You can read more about the request life cycle in Laravel in the official documentation at https://laravel.com/docs/5.2/lifecycle.

Artisan command-line interface

Nowadays, it is common practice to create web applications by using the command line; and, with the evolution of web development tools and technologies, this has become very popular.

We will mention that NPM is one of the most popular. However, for the development of applications using Laravel, we have an advantage. The Artisan CLI is automatically installed when we create a Laravel project.

Let's look at what the official documentation of Laravel says about the Artisan CLI:

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application.

Inside of the chapter-01 folder, we find the Artisan bash file. It's responsible for running all of the commands available on the CLI, and there are many of them, to create classes, controllers, seeds, and much more.

After this small introduction to the Artisan CLI, there would be nothing better than looking at some practical examples. So, let's get hands on, and don't forget to start Docker:

  1. Open your Terminal window inside the chapter-01 folder, and type the following command:
docker-compose up -d
  1. Let's get inside the php-fpm container and type the following:
docker-compose exec php-fpm bash

We now have all of the Artisan CLI commands available in the Terminal.

This is the simplest way to interact with the Teminal within our Docker container. If you are using another technique to run the Laravel application, as mentioned at the beginning of the chapter, you do not need to use the following command:

docker-compose exec php-fpm bash

You can just type the same commands from the next steps into the Terminal.

  1. Still in the Terminal, type the following command:
php artisan list

You will see the framework version and a list of all available commands:

Laravel Framework version 5.2.45
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under.
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
...

As you can see, the list of commands is very large. Note that the above code snippet, we did not put all the options available with the php artisan list command, but we will see some combinations on next lines.

  1. In your Terminal, type the following combination:
php artisan -h migrate

The output will explain exactly what the migrate command can do and what options we have, as seen in the following screenshot:

Output of php artisan -h migrate

It's also possible to see what options we have for the migrate command.

  1. Still in the Terminal, type the following command:
php artisan -h make:controller

You will see the following output:

Output of php artisan -h make:controller

Now, let's look at how to create the MVC in the Laravel application, using the Artisan CLI.

MVC and routes

As mentioned earlier, we will now create a component each of the model, view, and controller, using the Artisan CLI. However, as our heading suggests, we will include another important item: the routes. We have already mentioned them in this chapter (in our diagram of the request life cycle in Laravel, and also in the example diagram of the MVC itself).

In this section, we will focus on creating the file, and checking it after it has been created.

Creating models

Let's get hands on:

  1. Open your Terminal window inside the chapter-01 folder, and type the following command:
php artisan make:model Band

After the command, you should see a success message in green, stating: Model created successfully.

  1. Go back to your code editor; inside the app folder, you will see the Band.php file, with the following code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Band extends Model
{
//
}

Creating controllers

Now it is time to use the artisan to generate our controller, let's see how we can do that:

  1. Go back to the Terminal window, and type the following command:
php artisan make:controller BandController 

After the command, you should see a message in green, stating: Controller created successfully.

  1. Now, inside app/Http/Controllers, you will see BandController.php, with the following content:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class BandController extends Controller
{
//
}
As a good practice, always create your controller with the suffix <Somename>Controller.

Creating views

As we can see earlier when using the php artisan list command, we do not have any alias command to create the application views automatically. So we need to create the views manually:

  1. Go back to your text editor, and inside the resources/views folder, create a new file, named band.blade.php.
  2. Place the following code inside the band.blade.php file:
<div class="container">
<div class="content">
<div class="title">Hi i'm a view</div>
</div>
</div>

Creating routes

The routes within Laravel are responsible for directing all HTTP traffic coming from the user's requests, so the routes are responsible for the entire inflow in a Laravel application, as we saw in the preceding diagrams.

In this section, we will briefly look at the types of routes available in Laravel, and how to create a simple route for our MVC component.

At this point, it is only necessary to look at how the routes work. Later in the book, we will get deeper into application routing.

So, let's look at what we can use to handle routes in Laravel:

Code HTTP | METHOD |Verb

Route::get($uri, $callback);

GET

Route::post($uri, $callback);

POST

Route::put($uri, $callback);

PUT

Route::patch($uri, $callback);

PATCH

Route::delete($uri, $callback);

DELETE

Route::options($uri, $callback);

OPTIONS

Each of the routes available is responsible for handling one type of HTTP request method. Also, we can combine more than one method in the same route, as in the following code. Do not be too concerned with this now; we'll see how to deal with this type of routing later in the book:

Route::match(['get', 'post'], '/', function () {
    //
});

Now, let's create our first route:

  1. On your text editor, open web.php inside the routes folder, and add the following code, right after the welcome view:
Route::get('/band', function () {
return view('band');
});
  1. Open your browser to http://localhost:8081/band, and you will see the following message:

Hi i'm a view

Don't forget to start all Docker containers using the docker-compose up -d command. If you followed the previous examples, you will already have everything up and running.

Bravo! We have created our first route. It is a simple example, but we have all of the things in place and working well. In the next section, we'll look at how to integrate a model with a controller and render the view.

Connecting with a database

As we saw previously, the controllers are activated by the routes and transmit information between the model/database and the view. In the preceding example, we used static content inside the view, but in larger applications, we will almost always have content coming from a database, or generated within the controller and passed to the view.

In the next example, we will see how to do this.

Setting up the database inside a Docker container

It's now time to configure our database. If you use Homestead, you probably have your database connection configured and working well. To check, open your Terminal and type the following command:

php artisan tinker
DB::connection()->getPdo();

If everything goes well, you will see the following message:

Database connection message

For this example, however, we are using Docker, and we need to do some configuration to accomplish this task:

  1. Inside of the root project, open the .env file and look at line 8 (the database connection), which looks as follows:
 DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Now, replace the preceding code with the following lines:

 DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel-angular-book
DB_USERNAME=laravel-angular-book
DB_PASSWORD=123456

Note that we need to change a bit to get the Docker MySQL container directions; if you don't remember what you chose in the PHPDocker.io generator, you can copy it from the container configuration.

  1. Open docker-compose.yml at the root directory.
  2. Copy the environment variables from the MySQL container setup:
mysql:
image: mysql:8.0
entrypoint: ['/entrypoint.sh', '--character-set-server=utf8', '--
collation-server=utf8_general_ci']
container_name: larahell-mysql
working_dir: /application
volumes:
- .:/application
environment:
- MYSQL_ROOT_PASSWORD=larahell
- MYSQL_DATABASE=larahell-angular-book
- MYSQL_USER=larahell-user
- MYSQL_PASSWORD=123456
ports:
- "8083:3306"

Now, it's time to test our connection.

  1. In your Terminal window, type the following command:
docker-compose exec php-fpm bash
  1. Finally, let's check our connection; type the following command:
php artisan tinker
DB::connection()->getPdo();

You should see the same message as the previous screenshot. Then, you will have everything you need to go ahead with the example.

Creating a migrations file and database seed

Migration files are very common in some MVC frameworks, such as Rails, Django, and, of course, Laravel. It is through this type of file that we can keep our database consistent with our application, since we cannot versioning the database schemes . Migration files help us to store each change in our database, so that we can version these files and keep the project consistent.

Database seeds serve to populate the tables of a database with an initial batch of records; this is extremely useful when we are developing web applications from the beginning. The data of the initial load can be varied, from tables of users to administration objects such as passwords and tokens, and everything else that we require.

Let's look at how we can create a migration file for the Bands model in Laravel:

  1. Open your Terminal window and type the following command:
php artisan make:migration create_bands_table
  1. Open the database/migrations folder, and you will see a file called<timestamp>create_bands_table.php.
  2. Open this file and paste the following code inside public function up():
Schema::create('bands', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
  1. Paste the following code inside public function down():
Schema::dropIfExists('bands');
  1. The final result will be the following code:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBandsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bands', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bands');
}
}
  1. Inside of the database/factories folder, open the ModalFactory.php file and add the following code, right after the User Factory. Note that we are using a PHP library called faker inside a factory function, in order to generate some data:
$factory->define(App\Band::class, function (Faker\Generator $faker) {
return [
'name' => $faker->word,
'description' => $faker->sentence
];
});
  1. Go back to your Terminal window and create a database seed. To do this, type the following command:
php artisan make:seeder BandsTableSeeder
  1. In the database/seeds folder, open the BandsTableSeeder.php file and type the following code, inside public function run():
factory(App\Band::class,5)->create()->each(function ($p) {
$p->save();
});
  1. Now, in the database/seeds folder, open the DatabaseSeeder.php file and add the following code, inside public function run():
$this->call(BandsTableSeeder::class);
You can read more about Faker PHP at https://github.com/fzaninotto/Faker.

Before we go any further , we need to do a small refactoring on the Band model.

  1. Inside of the app root, open the Band.php file and add the following code, inside the Band class:
protected $fillable = ['name','description'];
  1. Go back to your Terminal and type the following command:
php artisan migrate

After the command, you will see the following message in the Terminal window:

 Migration table created successfully.

The preceding command was just to populate the database with our seed.

  1. Go back to your Terminal and type the following command:
php artisan db:seed

We now have five items ready to use in our database.

Let's check whether everything will go smoothly.

  1. Inside of your Terminal, to exit php-fpm container, type the following command:
exit
  1. Now, in the application root folder, type the following command in your Terminal:
docker-compose exec mysql mysql -ularavel-angular-book -p123456

The preceding command will give you access to the MySQL console inside mysql Docker container, almost exactly the same as how we gained access to php-fpm container.

  1. Inside of the Terminal, type the following command to see all of the databases:
show databases;

As you can see, we have two tables: information_schema and laravel-angular-book.

  1. Let's access the laravel-angular-book table; type the following command:
use laravel-angular-book;
  1. And now, let's check our tables, as follows:
show tables;
  1. Now, let's SELECT all records from the bands tables:
SELECT * from bands;

We will see something similar to the following screenshot:

Database bands table
  1. Now, exit the MySQL console with the following command:
exit

Using the resource flag to create CRUD methods

Let's see another feature of the Artisan CLI, creating all of the Create, Read, Update, and Delete (CRUD) operations using a single command.

First, in the app/Http/Controllers folder, delete the BandController.php file:

  1. Open your Terminal window and type the following command:
php artisan make:controller BandController --resource

This action will create the same file again, but now, it includes the CRUD operations, as shown in the following code:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BandController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

For this example, we will write only two methods: one to list all of the records, and another to get a specific record. Don't worry about the other methods; we will cover all of the methods in the upcoming chapters.

  1. Let's edit public function index() and add the following code:
$bands = Band::all();
return $bands;
  1. Now, edit public function show() and add the following code:
$band = Band::find($id);
return view('bands.show', array('band' => $band));
  1. Add the following line, right after App\Http\Requests:
use App\Band;
  1. Update the routes.php file, inside the routes folder, to the following code:
Route::get('/', function () {
return view('welcome');
});
Route::resource('bands', 'BandController');
  1. Open your browser and go to http://localhost:8081/bands, where you will see the following content:
[{
"id": 1,
"name": "porro",
"description": "Minus sapiente ut libero explicabo et voluptas harum.",
"created_at": "2018-03-02 19:20:58",
"updated_at": "2018-03-02 19:20:58"}
...]

Don't worry if your data is different from the previous code; this is due to Faker generating random data. Note that we are returning a JSON directly to the browser, instead of returning the data to the view. This is a very important feature of Laravel; it serializes and deserializes data, by default.

Creating the Blade template engine

Now, it's time to create another view component. This time, we will use the Blade template engine to show some records from our database. Let's look at what the official documentation says about Blade:

Blade is the simple, yet powerful, templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. All Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

Now, it's time to see this behavior in action:

  1. Go back to the code editor and create another folder inside resources/views, called bands.
  2. Create a file, show.blade.php, inside resources/views/bands, and place the following code in it:
<h1>Band {{ $band->id }}</h1>
<ul>
<li>band: {{ $band->name }}</li>
<li>description: {{ $band->description }}</li>
</ul>
You can find out more about Blade at https://laravel.com/docs/5.2/blade.
  1. Open your browser to http://localhost:8081/bands/1. You will see the template in action, with results similar to the following:
View of the template engine

Note that here, we are using the Blade template engine to show a record from our database. Now, let's create another view to render all of the records.

  1. Create another file, called index.blade.php, inside resources/views/bands, and place the following code in it:
@foreach ($bands as $band)
<h1>Band id: {{ $band->id }}</h1>
<h2>Band name: {{ $band->name }}</h2>
<p>Band Description: {{ $band->description }}</p>
@endforeach
  1. Go back to your browser and visit http://localhost:8081/bands/, where you will see a result similar to the following:
View template engine

Summary

We have finally finished the first chapter, and we have covered many of the core concepts of the Laravel framework. Even with the simple examples that we discussed in this chapter, we have provided a relevant basis for all of Laravel's functionality. It would be possible to create incredible applications with only this knowledge. However, we intend to delve deeper into some concepts that deserve separate chapters. Throughout the book, we will create an entire application, using a RESTful API, Angular, and some other tools, such as TypeScript, which we will look at in the next chapter.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • 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

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

Who is this book 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.

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
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 31, 2018
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781788833912
Vendor :
Google
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Publication date : Jul 31, 2018
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781788833912
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Hands-On Full Stack Web Development with Angular 6 and Laravel 5
€36.99
Hands-On Full Stack Development with Spring Boot 2.0  and React
€36.99
Hands-On Full Stack Development with Go
€32.99
Total 106.97 Stars icon

Table of Contents

12 Chapters
Understanding the Core Concepts of Laravel 5 Chevron down icon Chevron up icon
The Benefits of TypeScript Chevron down icon Chevron up icon
Understanding the Core Concepts of Angular 6 Chevron down icon Chevron up icon
Building the Baseline Backend Application Chevron down icon Chevron up icon
Creating a RESTful API Using Laravel - Part 1 Chevron down icon Chevron up icon
Creating a RESTful API Using Laravel - Part 2 Chevron down icon Chevron up icon
Progressive Web Applications with the Angular CLI Chevron down icon Chevron up icon
Dealing with the Angular Router and Components Chevron down icon Chevron up icon
Creating Services and User Authentication Chevron down icon Chevron up icon
Frontend Views with Bootstrap 4 and NgBootstrap Chevron down icon Chevron up icon
Building and Deploying Angular Tests Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 33.3%
2 star 0%
1 star 33.3%
Shlomi Asaf Oct 26, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm an experienced angular developer and I have been searching for a book that will help me to make the step for the full-stack world. I know NG but docker and PHP were not my sting side till now.Have read several but this one really did the trick for me. The writer guides you in a friendly and warm language., which makes the reading experience light and fun.
Amazon Verified review Amazon
Cristopher Barrientos Matamala Nov 08, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
El libro tiene muchos errores en el código, escribir el código a partir del libro resulta en muchos errores de compilación, porque muchas veces la ruta no es correcta, archivos aparecen con un nombre y luego aparece con otro nombre mas adelante, etc, sin el código fuente es imposible compilar correctamente el código a partir del libro.Para alguien con poca experiencia en ambos frameworks es difícil de seguir.Pero a pesar de todos lo mencionado anteriormente, cumple con el propósito de entregar las herramientas y el conocimiento para crear una app web en ambos frameworks.Lo que mas valoro del libro es los tips de buenas prácticas para realizar en ambientes productivos, además de mostrar como levantar la aplicación en ambiente develop y productivo. Me hubiera gustado que tuviera una sección de unit test en Laravel.
Amazon Verified review Amazon
superuser Jan 19, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
at some point, the text narrows to 1 character per line, centered. looked around the web and found hundreds of sources of this book available for free. buyers remorse.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela