Laravel 6 – Build Your First Laravel Application

Laravel 6 – Build Your First Laravel Application

Introduction

Laravel is a powerful MVC PHP framework. From official docs “Laravel is a web application framework with expressive, elegant syntax”. You must’ve heard about Laravel if you’ve ever worked with PHP. Laravel has experienced major growth since it’s initial release in 2011. Laravel was created by Taylor Otwell. It became the most starred PHP framework on GitHub in 2015.

My goal with this article is to create a guide for those who just want to learn Laravel and explore PHP. This article will not cover every small detail about Laravel but will be enough to get you started with Laravel 6.

Prerequisites

  • You should be familiar with HTML, CSS & most important Object-Oriented programming with PHP 7
  • A local PHP environment (Valet, Homestead, Vagrant, XAMP, LAMP, etc.)
  • A database (MySQL, SQLite etc.)
  • Composer
  • Node & NPM installed and updated

Note: For local environment I’ll be using LAMP (Linux Apache MySQL PHP) as there are no pre-configured environment like Homestead or Valet available for Linux. You can use Homestead for windows or Valet if you’re a Mac user.

I’ll explain how to create a new Laravel 6 application just as I would in real world environment. So let’s get started.

Planning

You must plan any project before coding it out. Planning a project before implementation is a major factor in its success. It doesn’t matter how you plan a project. You can plan it on Paper, whiteboard or some simple text file. You can also use Trello for planning out all the components you’re going to create in the project.

Today, we are going to create a Contact Book app. So let’s talk about goals of it.

  1. Display all contacts in a list.
  2. Create a form where people can add new contact.
  3. Validate the form.
  4. Insert the data into the database.

Get Started

Let’s create a brand-new Laravel project. I like to put all my projects in Development directory. Open your terminal and navigate to this directory.

mkdir Development
cd Development

Next, let’s install Laravel’s command line installer.

composer global require "laravel/installer"

Now, create a new Laravel project.

laravel new ContactBook

This will create a new directory at Development/ContactBook and install a stock Laravel app.

Navigate to newly created directory and run Laravel server by

cd ContactBook
php artisan serve

You’ll get this output, open your browser and navigate to given address.

Default Laravel Homepage

Hurray! You’ve successfully installed default Laravel application.

Laravel 6 Environment File

Let’s open this newly created project in Editor. You can use any editor or IDE of your choice. My personal favorite IDE for Laravel development is PhpStorm. Now open .env (Environment) file.

Laravel environment file

Here, you can set different environment variables. You can change the name of the app by editing ‘APP_NAME’. The main part here is ‘DB_*’ variables. You can set different database by specifying driver name. Here you can also set SMTP details.

Setting up Authentication

Laravel made it very easy to enable Login/Registration functionality. In this tutorial, it’s not mandatory to set up authentication, so you can skip this part if you want to.

Laravel’s laravel/ui package provides a quick way to scaffold all the routes and views you need for authentication using a few simple commands:

composer require laravel/ui --dev
php artisan ui bootstrap --auth
npm install && npm run dev

This command will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController will also be generated to handle post-login requests to your application’s dashboard.

With the basics set up and working, it’s time to start doing some coding.

Building a Contact List

Building a whole finished project is quite overwhelming, so it’s better if we divide our project in small parts. So let’s start with displaying a list of contacts. It may sound a small task but it still requires a database, table, view and query.

So let’s create a migration. We can create a migration by using Laravel artisan command line tool.

php artisan make:migration create_contact_books_table --create=contact_books

This command will create a new migration file database/migrations/{{datetime}}_create_contact_books_table.php

The file contains two methods: up and down. We’re interested in the up method for now. Add following columns in up method.

Schema::create('contact_books', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('phone')->unique();
            $table->text('description');
            $table->timestamps();
        });

Save it and run the migration by using following command.

php artisan migrate

Now, we’re going to need a model and some dummy data to work with our database. Laravel provides database seeder to populate table with dummy data and a factory class to generate dummy data.

php artisan make:model --factory ContactBook

This command will create a new Contact model. The --factory flag will generate a new factory file. Our newly created factory file will reside in database/factories. Open the ContactFactory.php file and fill the following:

$$factory->define(ContactBook::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'phone' => $faker->phoneNumber,
        'description' => $faker->paragraph,
    ];
});

Now, let’s create a database seeder for contacts.

php artisan make:seeder ContactBookTableSeeder

This command will create a new seeder for our contact book table. Open the seeder file by going to database/seeds/ContactBookTableSeeder.php. Now paste the following in it.

 public function run()
 {
     factory(App\ContactBook::class, 5)->create();
 }

To activate the following, navigate to database/seeds/DatabaseSeeder.php. Now paste the following in it.

public function run()
{
     $this->call(ContactBookTableSeeder::class);
}

Now, run the migration and seed the tables by running the following command.

php artisan migrate:fresh --seed

We have successfully generated fake data for our app! Now we’re ready to create a new view to display a list of Contacts.

Routes & Views

Now it’s time to provide new routes to display a form to add new contact and list existing contacts. We can add new routes to our application in the routes/web.php file.

Here, we can create necessary routes for our app. Laravel provides a default route. To create a new route, we can either use dedicated controller class or closure. For sake of simplicity we’re going to use closure in our app.

Now, let’s update the home route to show all contacts from database table.

Route::get('/', function () {
    $contacts = App\ContactBook::all();

    return view('welcome', ['contacts' => $contacts]);
});

Here, in second argument we’re passing an array of contacts to our view welcome.

Next, edit the welcome.blade.php view to display our list of contacts.

<div class="content">
    <div class="col-md-12 mt-5 mb-5">
        <div class="text-center mb-3">
             <h3>Contact Book</h3>
        </div>
        <table class="table table-striped table-bordered table-dark">
            <thead>
               <tr>
                 <th width="20%">Contact Name</th>
                 <th width="20%">Phone Number</th>
                 <th>Description</th>
               </tr>
            </thead>
            <tbody>
            @foreach ($contacts as $contact)
              <tr>
                 <td>{{ $contact->name }}</td>
                 <td>{{ $contact->phone }}</td>
                 <td>{{ $contact->description }}</td>
              </tr>
            @endforeach
            </tbody>
        </table>
   </div>
</div>

Refresh the page in your browser.

All Contacts, listed in a table

New Contact Form

Now, it’s time to add a new form so user can add their own contacts in our table. To do that, first create a new route in our web.php file.

Route::get('/add', function (){
   return view('add');
});

Next, create a new view add.blade.php in our views folder. Add the following code in it.

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-3">
                <div class="card">
                    <div class="card-header">
                        <h3>Add Contact</h3>
                    </div>
                    <div class="card-body">
                        <form action="/insert" method="post">
                            @csrf
                            <div class="form-group{{ $errors->has('name') ? ' has-error' : ''}}">
                                <label for="name">Name</label>
                                <input type="text" class="form-control" id="name" name="name" 
                                  placeholder="Name" value="{{ old('name') }}">
                                @if($errors->has('name'))
                                    <span class="help-block">{{ $errors->first('name') }}</span>
                                @endif
                            </div>
                            <div class="form-group{{ $errors->has('phone') ? ' has-error':'' }}">
                                <label for="phone">Phone</label>
                                <input type="text" class="form-control" id="phone" name="phone" 
                                 placeholder="Phone" value="{{ old('phone') }}">
                                @if($errors->has('phone'))
                                    <span class="help-block">{{ $errors->first('phone') }}</span>
                                @endif
                            </div>
                            <div class="form-group{{ $errors->has('description') ?' has- 
                             error':''}}">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" 
                                  name="description"
                                  placeholder="description">{{ old('description') }}</textarea>
                                @if($errors->has('description'))
                                <span class="help-block">{{ $errors->first('description') </span>
                                @endif
                            </div>
                            <button type="submit" class="btn btn-primary">Add</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

This will create a new form with 3 fields, name, phone and description. The form action is ‘/insert’ which we will next. Laravel require to send a csrf token with any type of form submission, so we’ve also included @csrf. This will create a hidden field with a random csrf token.

Navigate to ‘/add’ in your browser, you’ll see something like this.

Handling form submission

Now, with the form is created we can start working on our insert route, to handle the form submission. Open routes file and add the following.

use Illuminate\Http\Request;

Route::post('/insert', function (Request $request) {
    $data = $request->validate([
        'name' => 'required|max:100',
        'phone' => 'required|max:30',
        'description' => 'required|max:255',
    ]);

    $contact = tap(new App\ContactBook($data))->save();

    return redirect('/');
});

This route is a little complicated than others so let’s walk through it.

First, we are injecting the Illuminate\Http\Request object, which holds the POST data and other data about the request.

Next, we use the request’s validate() method to validate the form data. The validated fields are returned to the $data variable, and we can use them to populate our model.

We require all three fields, and using the pipe character; we can define multiple rules. If validation fails, an exception is thrown, and the route returns the user with the original input data and validation errors.

Next, we use the tap() helper function to create a new ContactBook model instance and then save it. Using tap allows us to call save() and still return the model instance after the save.

Now allow our model to populate given data, we’ve to specify “fillable” properties. Open ContactBook model and add the following.

class ContactBook extends Model
{
    protected $fillable = [
        'name',
        'phone',
        'description'
    ];
}

Now, let’s test this in our browser. Navigate to /add and submit the form with proper data.

Filling data in form
Our New Contact added to the bottom of the contact list

Conclusion

Congratulations, you’ve created your first Laravel 6 app. This article was designed to get you started on building your app, and you can use this as a building block to gain the skills you need to develop your application.

I hope you liked this article. Subscribe to our mailing list for more articles by me. Have a great day!

How to create a WordPress Plugin

How to create a WordPress Plugin

Introduction

What is WordPress? A technical definition is “WordPress is an open source content management system (CRM) built in PHP”. Currently WordPress is the most popular CRM available for free! If you’ve ever used WordPress, you definitely know about themes & plugins in WordPress! In this article I will show you how to create a simple WordPress plugin in less than 15 minutes! But first, let’s talk more about what a plugin actually is.

Take a look at our fresh PHP 7 Introduction.

What is a WordPress Plugin?

WordPress plugin is a package of PHP script(s) that can alter your website. A plugin can alter your website in many ways i.e. From adding a simple message in header to creating a whole shop on your website eg. WooCommerce. Plugins can also modify/tweak existing features of your website like changing Login, sending email on specific event etc.

WordPress theme or Plugin?

If you have ever opened a WordPress theme, you’ll know that every theme contains a function.php file. This file contains all the theme related logic and any functionality provided by a particular theme. You can modify this file and add your own custom functionality too. So if we can directly add new feature in function.php, why do we need a plugin? Well the answer is simple, if you only want to add some text in the header or something small like that, you can surely use theme’s function.php. If you want something like a custom chat bot or anything like that, then a plugin would better suit your needs.

The main difference between a theme’s ‘function.php’ and separate plugin is that plugin’s functionality persists regardless of your website’s current theme but any changes from function.php will only be applicable when that particular theme is in use.

Creating our first WordPress Plugin

WordPress plugin’s default structure only requires one PHP file in a separate directory with a PHP block comment containing various data about that plugin. So, to create a plugin you need to navigate to your wp-content/plugins folder. Create a new folder name myFirstPlugin. Inside this new folder create a new file named myfirstplugin.php. Open the created file in any text editor of your choice and paste the following in it.

<?php
/*
Plugin Name: My First Plugin
Plugin URI: http://mywebsite.com/
description: My first ever WordPress plugin
Version: 1.0
Author: Arman Khan
Author URI: https://instagram.com/codingwitharman
License: GPL2
*/

Here, only Plugin Name is required, but it’s a good practice to provide as much data as possible about our plugin.

That’s it!! You’ve created your first ever WordPress plugin. You can log in to your wp-admin and go to plugins and active this plugin. Of course, this plugin does not do anything, yet! But it is an active plugin.

How to create a great plugin?

There are some parameters that you should consider while creating your plugin. These parameters will help you create a successful well documented plugin.

Plugin Structure

How to structure your plugin? Well, this question is quite common among new WordPress developers.

If your plugin provides complex functionality, you should divide it in multiple files. For example, if your plugin has a main class, you should put that in your plugin’s main file and provide connections to other files through it. If your plugin includes UI related files, you should consider sorting them in separate folders like JS/CSS/Images and put all these folders in one assets folder. Well of course this is not a requirement from WordPress but a good plugin structure is always preferred compared to a bad one.

Naming Convention

When creating functions in the plugin, you should be very careful naming them. You should never choose more general names for your functions as it might clash with other plugins that have similar functionalities.

The most common solution is to use unique prefix. For example, if your function name is commonFunction then you should replace it with something like ak_commonFunction.

Helper Hooks

WordPress offers three hooks for custom plugins.

register_activation_hook()

This hook allows you to create a function that runs when your plugin is activated. You can use this hook to load dependencies, check for plugin version or check for WordPress or PHP version.

register_deactivation_hook()

This hook when your plugin is deactivated. You can use this hook to un-load dependencies, remove settings etc.

register_uninstall_hook()

This function runs when a WordPress administrator delete your plugin from backend. This is a great way to remove plugin specific data like tables in database or custom field created by your plugin.

Wrap Up

Well, so now you know how to create a simple WordPress plugin. Now you can easily follow articles that require you to create WordPress plugin first. Of course this guide does not contain advance features that a plugin can provide, we’ll cover those topics in future articles for sure. Stay tuned!

Complete Vue.js 3 Guide

Complete Vue.js 3 Guide

Last updated: 24.12.2019

We at German IT Academy are very eager to see first official release of the third Version of Vue.js 3. Therefore we are watching the developments closely and will be publishing many Posts, Tutorials & Courses on Vue.js 3. It does pay off to be on our Newsletter list (scroll down to subscribe) or check this Vue.js 3 Guide once i a while.

Also, check out the first “awesome-vue3″ repository with an updated and curated list of all resources regarding Vue.js 3.

Currently the vuejs team is working on three projects: the 2.7 Version, Maintenance of current codebase and the Roadmap (mainly the third version of Vue.js).

Major Changes in Vue.js 3

Let’s explore the official plans for third Version of Vue.js. We will also derive a great lot of content from the vue/rfcs, where all the RFCs are developed and discussed (Note: RFC = Request For Comment). We picked some of the most interesting ones and included a basic code example. As the changes become more certain, we will update our Vue.js 3 Guide to have more detailed examples.

Official RFCs December 2019

Composition API

There is a long explanation of what the Composition API is. Generally, the motivation behind it is the reuse of Logic, better Code Structure and better Type Inference. Here is a basic Example:

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>

<script>
import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2)
    })

    function increment() {
      state.count++
    }

    return {
      state,
      increment
    }
  }
}
</script>

New syntax for scoped slots usage

  • New directive v-slot that unifies slot and slot-scope in a single directive syntax.
  • Shorthand for v-slot that can potentially unify the usage of both scoped and normal slots.
<!-- default slot -->
<foo v-slot="{ msg }">
  {{ msg }}
</foo>

<!-- named slot -->
<foo>
  <template v-slot:one="{ msg }">
    {{ msg }}
  </template>
</foo>

Shorthand syntax for the v-slot syntax

<foo>
  <template #header="{ msg }">
    Message from header: {{ msg }}
  </template>

   <template #footer>
    A static footer
  </template>
</foo>

Dynamic values in directive arguments

<div v-bind:[key]="value"></div>
<div v-on:[event]="handler"></div>

# instead of

<div v-bind="{ [key]: value }"></div>
<div v-on="{ [event]: handler }"></div>

Global API

Currently in 2.x, all global APIs are exposed on the single Vue object:

import Vue from 'vue'

Vue.nextTick(() => {})

const obj = Vue.observable({})

In 3.x, they can only be accessed as named imports:

import Vue, { nextTick, observable } from 'vue'

Vue.nextTick // undefined

nextTick(() => {})

const obj = observable({})

Re-design app bootstrapping and global API

Global APIs that globally mutate Vue’s behavior are now moved to app instances created the new createApp method, and their effects are now scoped to that app instance only.

// Before
import Vue from 'vue'
import App from './App.vue'

Vue.config.ignoredElements = [/^app-/]
Vue.use(/* ... */)
Vue.mixin(/* ... */)
Vue.component(/* ... */)
Vue.directive(/* ... */)

new Vue({
  render: h => h(App)
}).$mount('#app')


// After
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp()

app.config.ignoredElements = [/^app-/]
app.use(/* ... */)
app.mixin(/* ... */)
app.component(/* ... */)
app.directive(/* ... */)

app.mount(App, '#app')

More Material on Vue.js 3

  • Github Repository ‘awesome-vue3‘ with a compilation of most recent and most popular Vue.js 3 Resources.
IT Career Path Nobody Is Discussing

IT Career Path Nobody Is Discussing

Whatever path you decide on, we will help you find out the ideal things to do to take. Your career path contains the jobs you should hit your final career objective. While the career path will appear different for everybody, aiming to acquire equal parts experience in company and technology is your safest bet. For that reason, it’s essential you select the ideal career path to ensure it’s authentic to who you are.

Nuance of IT Career Path

For midmarket CIOs, it’s an incredibly exciting prospect for them to not only grow their careers but also to make a great deal of money,” Banerji explained. Information Technology (IT) careers are predicted to experience significant growth during the present decade. When you’re ready to take that very first step into your new IT career you will begin with the fundamentals.

Roadmap for IT Career Path

One particular tangible way to begin your career change is by way of freelance or part-time work. As soon as you have decided that a career change is certainly the way forward, there’s still a lot you will need to think about. Making a career change is just one of the toughest job-search challenges. Career change, as soon as you have decided that a career change is certainly the way forward, there’s still a lot you will need to think about. Whether the career change is voluntary or involuntary, individuals may experience a number of emotions like fear, anxiety, or a feeling of loss. Tons of individuals wonder whether making a significant career change is well worth it.

The Foolproof IT Career Path Strategy

Figure out if career change is appropriate for you and how to change careers. Irrespective of where you currently are in your career, there are a couple of things you can begin doing to increase your odds of a thriving future IT career path. Another way to go into a career in information technology is to make a college degree. Online Courses are a quicker way though. In addition you get the most up to date skills.

You are able to still receive the job. You can proceed and apply for jobs that you believe you’d enjoy, whether you’ve got the requirements listed in the work ad or not. Simply perusing books about the market, in addition to specific topics like programming and networking, can help you explore the range of work in the area.

Growing & Goal

Much like any goal, it can help to define where you wish to go and a path to get there. It’s possible to segue from just about any career path into any other. You’re able to pursue a few different, new career paths simultaneously.

As you grow, however, the path forward can come to be not as clear. A career path provides the employee a feeling of direction, a way to evaluate career progress, and career targets and milestones. Before you go out and select a career path, it’s imperative that you take the opportunity to figure out what success means to you. Whichever way a career path takes someone, it’s intended to provide greater satisfaction of a worker’s career values and requires by targeting a string of jobs created to receive them to their career objective. Other career paths are indirect and could involve work in various industries or kinds of jobs, including when someone is working on a career change.

Awesome Future of Frontend in 2020

Awesome Future of Frontend in 2020

Before we dive in to Future of Frontend in 2020. Let’s begin with some basics as we gradually get more forward-looking. We obviously cannot know what technology will dominate in 2020 and what framework will pop up. But we can try at least.

What is frontend?

Frontend is referred to as the pattern of transforming data to a graphical interface with the use of CSS, HTML, and JavaScript, so that users can easily view and efficiently interact with the data. It distinctively translates a computer programming source code into an intermediate illustration to produce code in a computer output language.

It is also a common term used by programmers and computer programmers to describe part of the layers that make up a website, computer program or hardware, which are depicted based on how accessible they are to a user. The frontend layer strategically placed on top of the backend includes all software or hardware that is part of a user interface.

Professionals such as web designers usually handle Frontend section of every project and the components are customer facing. Some of these components includes:

  • Search engine optimization (SEO)
  • Graphic design and image editing tools
  • Design and markup languages such as CSS and HTML
  • Web performance and browser compatibility
  • Usability and accessibility testing

Frontend Career

Frontend career is an interesting area with availability of various great remunerations as a profession that becomes easier with the adequate knowledge of the three primary coding languages i.e. CSS, HTML and JavaScript. Research has deducted that frontend development is and will always be a good career path for humans because software keeps evolving every day.

The consistent demands for frontend career specialist is very high. Some of the key skills of a frontend developer are responsive design, frameworks, debugging, web performance, CSS preprocessing and command line among others.

Consider taking our VueJS Certification or VueJS Online Course. It’s on-demand, easy to understand and has tremendous benefits for you career.

Relevant Areas of Frontend

An important area where frontend (client-side programming) is of high relevance is UI, UX. There is a distinct relationship between frontend, UI and UX. They work together seamlessly. The UX design centered on the satisfaction of the user experiences with software. Frontend development is the technical implementation of the software user interface.

UI design is the graphical bridge that connects the UX and frontend. An individual can choose to be a UI, UX, and frontend web developer in which he/she will be responsible for applying interactive and visual design experience. For you to be successful in this field, you must be able to observe users behavior to bring the best out of an application. Your primary aim should be to ensure user-based company goals are been reached satisfactorily. Some of the major importance of frontend development in relationship with UI and UX are:

  • Optimize navigation: Intuitive navigation will help gain customer trust by ensuring that the visitors find whatever they are seeking from your site. It majorly comprises of a well-planned site layout, clean, and structured impressive graphics.
  • Visitor retention: This will help increase traffic and conversion. Thus, optimized performance is one of the business benefits of front-end development.

Some other sub areas of its relevance are mobile frontend and web frontend:

  • Mobile Frontend: This can operate effectively without an active internet.
  • Web Frontend: This requires active internet for it work properly on your devices.

Generally, frontend development tools are focused on the user interface and user experiences. These has given birth to the following importance:

  • Creating modern day responsive websites or web app for mobility segment
  • Building bug free, secured and consistent products for high traffic web zone
  • Developing quickly reacting features or interactive app tools for online stores
  • Easy to learn, use and scale technologies, etc

In conclusion, the earlier you learn various frontend skills such as VueJS today – the better. Frontend courses are made easy with the best-qualified teaching procedures at German IT Academy.

Frontend in 2020

As for the prediction of where Frontend will head in 2020 it’s no easy task. Just as VueJS came out of nowhere and allowed more people with lower frontend skills to participate in the development. So can another framework, paradigm or tools do so in 2020.

Responsive stays

It is certainly though that Material Design & Bootstrap are going to continue growing like they already do. They will keep evolving and doing the little hard jobs of micro-designing small buttons and tables for us.

Changing Screen Sizes

If the rise of foldable phones continues, the frontend developers will need to adjust to this new environment of suddenly changing screen size and making sure that the app, page, game works transitions seamlessly between both screen sizes.

Performance & Data Focus

With the rise of data lakes and data on itself, Frontend Industry will be coming up with ways to make their Application lighter and more intelligent in showing, grouping and filtering the right information without overloading the hardware, browser, etc.

Artificial Intelligence in Frontend

With AI supported in-app & on website behaviour analysis of end consumers. We will have insight into deep psychology of our brains. What color triggers more excitement, what button animation triggers more dopamine, etc. The Frontend world will definitely become more fine tuned to our psychological “needs” in our to manipulate the end consumer to … consume.

Frontend in VR & AR

It’s totally new field for us. But one can imagine that Frontend will play a crucial role in AR and VR. This area brings a whole new set of challenges with itself. The user does not use a mouse or a keyboard. The user does stare a small screen. There could pop up a Framework like “ReactVR” (e.g. React 360) or something like that. Which would allow you do design 360 User Interfaces. Or something like “VueAR”, which would allow you to create transparent overlay User Interfaces to allow the user to use your app while they are interacting with their environment.

Node.JS Tutorial: REST API & CRUD Operations

Node.JS Tutorial: REST API & CRUD Operations

The following Tutorial will guide you through creating a simple REST API and CRUD Operations. Our Stack is ExpressJS, Mongoose and MongoDB.

This API will perform CRUD Operations on Data stored in MongoDB. It’s best to start from scratch and try creating this app by yourself. After you tried creating the App with the help of this tutorial, you can go ahead and clone the working Github Repository here. https://github.com/AndreyBulezyuk/nodejsrestapi


Before you continue with this tutorial, please consider signing up for our Mailing List. You’ll get awesome free tutorials, podcasts, free and paid courses into your inbox.


What is REST API and CRUD Operations

REST stands for representation state transfer (wiki) and stands for a software architectural style with a set of constraints which lead to REST Service. Our service (our ExpressJS Server) is an Adapter to another backend service or database. Therefore we call it API.

CRUD is much simpler. The letters stand respectively for Create, Read, Update and Delete. Thus, CRUD stand for a set of operations that allows us to manipulate our states or data (through our REST API).

NPM – Creating the Project

Creating the project is the first step. Create a folder and inside that folder type

npm create

Fill out the following promts that’ll appear after npm create. Then we need to install following packages for our project:

npm install --save express@4.17.1
npm install -g nodemon@1.19.4
npm install --save mongoose@5.7.11

Once there, you should have a file ‘package.json’ in your folder that look like the code below. Note that i added “dev” to “scripts”, where we call nodemon. Nodemon allows us to restart the server automatically as soon as we update a file in our project.

{
  "name": "nodejsboostrap",
  "version": "1.0.0",
  "description": "Basic NodeJS Excercise for German IT Academy (git-academy.com)",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "keywords": [
    "nodejs",
    "germanitacademy",
    "gitacademy",
    "expressjs",
    "nodemon"
  ],
  "author": "Andrey Bulezyuk @ German IT Academy",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.7.11"
  }
}

In schema/ i added a new schema product.js which is pretty similar to the one you will find in the official docs. This is the Object Schema that we will be working with.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var productSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  price: Number,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now }
});

var Product = mongoose.model('products', productSchema);
module.exports = Product

If you want to learn how to build VueJS Applications that can read from a REST API, take a look at our new VueJS Certification.

Express.JS – REST API Routes

Our Express.js backbone is pretty tiny, only 8 lines of code. We tell Express to use a bodyParser, so we can access the body as a JSON Object. We tell ExpressJS to use our product route and then we start the server.

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const product = require('./routes/product')

app.get('/', (req, res) => res.send('Hello from German IT Academy!'))
app.use(bodyParser.json())
app.use('/product', product)
app.listen(3000, () => console.log(`Example app listening on port 3000!`))

Just a quick test whether the server is up and ready!

C:\Users\andre>curl localhost:3000
Hello from German IT Academy!

Looks good. Now. Our product route is where all the magic actually happens. All our Documents in MongoDB will be created, read, updated and deleted from this place: routes/product.js.

Now let’s got through each Route (GET, POST, PATCH, DELETE) and see what mongoose method we used to make this work. Note, this is not the ultimate way to do it. Feel free to try out different Methods provided by Mongoose.

The first Route is a GET Route. Which means it only return the Entries in the Database by executing:

router.get('/', async function (req, res) {
    const products = await product.find().exec()
    res.send(products)
})
REST API Request with User Interface for REST API
A simple GET Request, to test whether our API returns the entries from MongoDB.

The POST Route insert new Entries into the MongoDB Database. It uses the data from the Request payload in JSON Format. It’s important to notice that the body payload has to have the right set of Attributes. Meaning that the Request initiator must know what Attributes a Product can/must have.

router.post('/', function (req, res) {
    product.create(req.body)
    res.send('POST Request accepted.')
})

The Patch Route is a bit more complicated. It is cause by the MongoDB Syntax of updating a Document. If we want to update only some Attributes/Keys of a MongoDB Document, we must use the key “$set: {}”. The req.body contains the updated values of attributes/keys for the specified Document. We specify what document to update via the URL Parameter id. Finally we’ll search through MongoDB for an Entry with the corresponding MongoDB “_id”!

router.patch('/:id', async function (req, res) {
    const result = await product.updateMany({
        "_id": String(req.params.id)
    }, { $set: req.body })
    res.send('PATCH Request accepted.')
})

Last and but not least, the Deletion of a Document. The Delete Route. We specify the “_id” of the DOcument in the URL and invoke the Mongoose DeleteMany() Method.

router.delete('/:id', async function (req, res) {
    const result = await product.deleteMany({
        "_id": String(req.params.id)
    })
    res.send('DELETE Request accepted.')
})

That is it, we are done, but, you probably want to see the whole code? Here you go:

var express = require('express')
var router = express.Router()
const mongoose = require('mongoose')
const product = require('../schema/product')
mongoose.connect('mongodb://localhost/nodejsrestapiboostrap', {
    useNewUrlParser: true,
    useUnifiedTopology: true 
});


router.get('/', async function (req, res) {
    const products = await product.find().exec()
    res.send(products)
})

router.post('/', function (req, res) {
    product.create(req.body)
    res.send('POST Request accepted.')
})

router.patch('/:id', async function (req, res) {
    const result = await product.updateMany({
        "_id": String(req.params.id)
    }, { $set: req.body })
    res.send('PATCH Request accepted.')
})

router.delete('/:id', async function (req, res) {
    const result = await product.deleteMany({
        "_id": String(req.params.id)
    })
    res.send('DELETE Request accepted.')
})

module.exports = router