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!

Getting started with PHP 7 in 2020

Getting started with PHP 7 in 2020

What is PHP?

PHP stands for Hypertext Preprocessor (earlier called “Personal home page”). It is an open source scripting language created for the web development. PHP is a server-side language which means all the code is rendered on server and only static HTML, CSS and JavaScript is sent to the client’s browser. PHP is a back-end language which means no one on client side can check the code written in PHP, only the person with authority to access the server can check the source code. Now let’s explore reasons to learn PHP 7 in 2020 and what lies ahead for this simple and beautiful language.

Why should I learn PHP 7 in 2020?

PHP is compatible with all leading operating systems such as Windows, Linux, MAC OS and many others. Likewise, it is compatible with all popular web servers such as Apache, NGINXm IIS etc. PHP7 offers great compatibility and performance. Not only is it open source but also it contains many features and it is absolutely easy to install and set-up. We will cover installation part later in this article.

What are features of PHP?

PHP comes with many benefits that let you create wonderful web applications.

1. Open Source

PHP is an open source programming language which means it is free to use. There is a great community to help you if you get stuck anywhere and not able to figure out the problem.

2. Cross-Platform

PHP supports all major operating systems and servers.

3. Easy to use

PHP is simple and clean scripting language. Its syntax is convenient to use. Anyone can quickly learn PHP.

4. Performance

It is one of the fastest programming language. It takes so little time to establish a connection with database or fetch data from web services.

How to install PHP7?

You can follow this guide to install PHP7 in your preferred operating system.

Windows :

Step 1 – Download PHP7

Go to the official PHP website and download the latest version. Save it on your windows PC.

Figure 1

Step 2 – Extract the zip

Figure 2

Step 3 – Setting up Environment variable

We need to configure the environment variable to access PHP from the command line. You can follow these steps to do so.

Right click -> My Computer (This PC) -> Properties -> Advanced system settings

This will open a the following window.

Figure 3

Now click on Environment variables, select path under the System variables section and edit. Add the path of installed PHP to system path.

Click on the new button and add the path to the PHP bin. Save all changes and close all the windows. Now to verify the settings, open console (or CMD) and execute following.

FIgure 4

If you get the following output, it means PHP is successfully installed on Windows.

Linux:

Here, we will see the steps to install PHP in Ubuntu Linux.

Step 1 – Update Ubuntu

Before installing anything new, you should always update your system. Open a terminal and run the following commands:

apt-get upgrade && apt-get update

Step 2 – Install PHP7

You can install PHP7 from Ubuntu’s official repository by following command:

apt-get install php

This command will install PHP7 and it’s required dependencies. To check whether PHP is installed or not execute following command:

php -v

It will return the PHP version related information.

PHP7 Syntax Overview

Like any other programming language PHP has a set of syntax rules which we need to follow while programming. PHP files commonly have a .php file extension as they’re always executed on server.

Tags in PHP or Escaping to PHP

The PHP parsing engine needs a way to differentiate PHP code from other elements. PHP tags are used for this.

We can ‘Escape to PHP’ by using the following 4 methods:

  1. Canonical PHP tags
  2. SGML (or) Short HTML Tags
  3. HTML Script Tags
  4. ASP Style Tags

From all of the above, Canonical PHP tags are most commonly used and are compatible with majority of servers.

Example:

<?php
    # Here the echo command prints the message
    echo "Hello world";
?>
Comments in PHP

Comments are statements in a program by developers which describe the intent and purpose of the code. There are 2 styles for comments in PHP. Comments in PHP code are not read or executed by the PHP engine. Therefore, they do not affect the output.

Single Line Comment

<?php
// This is a single line comment

echo "Hello World";

# This is also a single line comment
?>

Multi line Comment

<?php
/* 
Example for multiline comment
This is a multiline comment
*/

echo "Hello world";
?>
PHP Syntax is Case-Sensitive

In PHP besides variables, all other keywords are not case-sensitives. We have to be very careful while defining and using variables. Look at this example.

<?php
// Here all echo statements will execute
// in the same manner because keywords are case-insensitive

$variable = "Test";
ECHO $variable;

// You will get an "Undefined Variable" error
// Because variable names are case-sensitives

echo $VARIABLE;
?>

If you want to build a fast and beautiful Frontend for you PHP-Backend Application, consider the popular Framework Vue.JS 2 Course.

PHP Data types & Variables

Data Types

A Data type is the classification of data into a category according to its attributes. There are 4 major data types in PHP.

  • Integer – eg. 1, 1000, -12
  • Float – eg. 3.14
  • String – eg. “Test String”
  • Boolean – eg. True or False
Variables

A variable is a name given to a memory location that stores data at runtime. There are 2 types of variables, Global variables and Local variables. There are some pre-defined rules to create variables.

  • All variable names must start with the dollar sign. – eg. $testVariable
  • Variable names are case sensitive.
  • All variable names must start with a character.
  • Variable names must not contain any whitespaces between them.

PHP Control Structure – If else

If else is the simplest control structure. And it is relatively easy to understand even in PHP 7 in 2020. It evaluates the conditions using Boolean logic. Take a look at the following code snippet:

<?php
if (condition is true) {
   // Code block one
}else {
   // Code block two
}
?>

Here,

  • “(condition is true)” is the control structure, if it evaluates to true, “Code Block one” will be executed
  • If condition evaluates to false, “Code block two” will be executed.
  • In any situation only one of the following blocks will be executed.
<?php

// If else example

$x = 10;
$y = 20;

if($x > $y) {
    
    echo "$x is greater than $y";

} else {

    echo "$y is greater than $x";

}

// Output: 20 is greater than 10

?>

PHP Loops

While Loop

The while loop is use to execute a block of code repeatedly until the codition gets statisfied.

<?php

while (condition) {
    // Code to execute
}

?>

Here,

  • Code inside of while loop will be executes until the given “condition” is true.
<?php

$i = 0;

while ($i < 5) {
    echo $i;
    $i++;
}

/*
Output:

0
1
2
3
4

*/

?>
For Loop

For loop executes the block of code a specified number of times.

<?php

To (initialization; condition; increment/decrement) {

    // Code to be executed

}

?>

Here,

  • “initialize” is used to set the counter’s initial value.
  • “condition” is the condition that is evaluated for each loop iteration.
  • “increment/decrement” is used to increment or decrement the counter.
<?php

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

/*
Output:
0
1
2
3
4
*/

?>
ForEach Loop

The php foreach loop is used to iterate through array values.

<?php

foreach($array_variable  as $array_value){

    //Code block to be executed

}

?>

Here,

  • $array_variable is the array variable to be looped through.
  • $array_value is the temporary variable that holds the current array item.
<?php

$arr = [1, 2, 3, 4, 5]

foreach ($arr as $item) {
    echo $item;
}

/*
Output:
1
2
3
4
5
*/

?>

Executing PHP File

There are two ways to execute PHP files.

  1. Executing PHP file in browser
  2. Executing PHP file in terminal (command line)
Executing PHP file in browser

Step 1: Create your PHP file in www or htdocs folder of your server.

Step 2: Turn on your server.

Step 3: Go to http://localhost/<file_name>

Figure 5
Executing PHP file from terminal (command line)

Step 1: Open your preferred terminal

Step 2: Navigate to your file location (directory)

Step 3: Execute the file by following command

php <filename.php>
Figure 6

As you can see, it will one of the best skills you could acquire for yourself and your resume. We are certain that PHP 7 in 2020, will have a continuously growing community.