Thursday, 30 March 2017

Topic (Angular) 1 - Angular Introduction

Getting Started


Angular is a another way from javascript to make use of html to be more readible an reduce response time between client and server side. This will create a dynamic and at the same time a responsive website application. Angular JS act as behind curtain to implement data that being load from server side without refreshing the whole page.


What basically happen ?

1. When user click on link this will create new HTTP request.
2. Server side will response in JSON data .
3. Client Side will update the browser using the response from server side.


Requirement

1. Download Angular 
2. Download CSS


Directives 

A directive is a marker on HTML tag that tells AngularJS to run or reference the javascript.

Example . In index.html 

<html> <body ng-controller="ExampleController"> .... </body> </html>

and in our javascript  app.js

function ExampleController(){
 alert('Hello!');
}

this will bind the html with Angular Javascript.


Module

Creating our first module which we can write in app.js file.

var app = angular.module ('store, []);


To include  our module inside our html we can use ng-app syntax and apply it in <html> tag. Like this :
<html ng-app = "store">

Expressions

Expressions allow developer to display dynamic value  into your html . The concept <? php echo ?> will be replace double curly bracket  {{    }} .

Numerical Operations example :
<p>  I am {{  4 + 6 }} years old </p> 
This will produce a result :  I am 10 years old


String Operations example : 

<p> {{ "Hello my name is " + "yourname"}}  </p> 
This will produce a result :  Hello my name is yourname


Monday, 27 March 2017

Topic 15 - Custom Helper

Basically you need a helper , when you going standardize a certain function or code that going to be used at any view pages. This roughly bring the idea of using custom helper on which we can use the same code either to create buttons, forms or any elements that contain the same code.

There are few steps that we can follow in order to create custom helper :

First, you can create helper file in  app/helpers.php

There you can fill your own helper code and ready to be use.

<?php
// My helper function
function fullName($stringA,$stringB)
{
    return $stringA .' '. $stringB;
?>

In the example given, we are creating a helper function to combine firstname and lastname for our user using the fullName function. Then, we can assign our helper file into composer.json  autoload files.
{
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
}

And after that , run composer dumb-auto command on cmd

$ composer dump-auto

If you intent to include many helpers , then it will be better if you create helper files inside Helper folder just like this app/http/Helper/YourHelperName.php

Create a new helper file that will loop dynamically the required helpers. An example we named our file  HelperServiceProvider.php

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

Then register your helper folder inside service provider located at config/app.php


'providers' => [
    'App\Providers\HelperServiceProvider',
]
References :

https://laracasts.com/discuss/channels/general-discussion/creating-custom-helpers?page=1
http://laravel-recipes.com/recipes/50/creating-a-helpers-file

Topic 14 - Laravel Helpers

Tuesday, 21 March 2017

Topic 13 - Middleware

What is Middleware?

Basically middleware is a mechanism for filthering HTTP request entering your application. Middleware can be such allowing authenthicated users to redirect to a certain page without re-entering username and password onto login page again. Middleware are located in the app/Http/Middleware directory.

To create new middleware, we can use make:middleware Artisan command.

php artisan make:middleware CheckMaleGender

This will create new middleware file at app/Http/Middleware directory. The middleware we just create is to let male user can enter the application or otherwise redirect them back to home page.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckMaleGender
{
    public function handle($request, Closure $next)
    {
        if ($request->gender != 'male') {
            return redirect('home');
        }

        return $next($request);
    }

}
We also can control either the middleware happens before or after a request. It depends the location variable $request we declare inside the middleware .

For example, the code below shows the middleware will trigger before a request ;

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Do something with your code
        return $next($request);
    }
}

While , the code below shows the middleware will runs after a request received ;

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Do something with your code
        return $response;
    }
}

Registering A Middleware


Developers have an option where the middleware can be run on every HTTP request by placing them in global middleware in the $middleware property inside app  app/Http/Kernel.php directory ;


protected $middleware = [

      \App\Http\Middleware\CheckMaleGender::class
];

However , if the developers want to specify the middleware on a specific route, they can declare inside  $routeMiddleware property ;

protected $routeMiddleware = [
    ...
    'male' => \App\Http\Middleware\CheckMaleGender::class,
];
After the middleware has been assigned in  app/Http/Kernel.php directory , developers can attach them on Routes inside routes/web.php .

use App\Http\Middleware\CheckAge;

Route::get('customer/gender', function () {
    //
})->middleware(CheckMaleGender::class);

Authorization Via Middleware


Middleware also works well with authorization where develepors can authorize actions on user "role" who can access before or even incoming request.

Example of authorization :

use App\Customer;

Route::put('/customer/{id}/update', function (Customer $customer) {
    // The current user may update the post...
})->middleware('can:update,customer');

References :

https://scotch.io/tutorials/understanding-laravel-middleware
https://laravel.com/docs/5.4/middleware

Monday, 20 March 2017

Topic 12 - Service Container

Previously on laravel 4 , Service container was known as Inversion of Control (IoC) Container. As a Laravel developer, understanding and using the Service Container properly is a crucial part in mastering your craft, as it is the core of any Laravel application.

The term "Bind" is a common use of word that works with interfaces implementation , directories and other important things that make Laravel application run smoothly. Bind will produce a single Object that contains all of various bindings and it is very easy to retrieve them back or "resolve" them at any point of code.


Binding & Resolution

For the very basic, let say we have a certain Class DeliveryService that provides some particular service.

public class DeliveryService
{
    public function __construct()
    {
         //code here
    }

      public function doSomething()    
     {
         //code here
    }
How do we bind? 

Binding a service class is simple as line of code below

$this->app->bind('DeliveryService', \App\Services\DeliveryService::class);
Remember to always bind your services within the register method of your service providers.


How to use?

You can use the service binding using the example code:

$deliveryService = new \App\Services\DeliveryService();
$deliveryService->doSomething();
This will call the method inside DeliveryService class .


How do we resolve?

app()->make('DeliveryService')->doSomething();

With service container the code will look elegance and easy readable. Thus, the code will be much more cleaner.



References :

https://dotdev.co/understanding-laravel-service-container-bd488ca05280#.7g168fjgz
https://websanova.com/blog/laravel/10-reasons-why-laravel-is-better-than-codeigniter
https://laravel.com/docs/5.4/container#introduction

Topic 11 - Mail Notifications

Laravel comes out with email notification features provide a proper feedback for user.

First of, to create new mail notification you can write in CMD on your project folder

php arisan make:notification YourNotification

Then you can configure how your notification looks like in Notifications/YourNotification.php folder :
public function toMail($notifiable)
{
    $url = url('/invoice/'.$this->invoice->id);

    return (new MailMessage)
                ->greeting('Hello!')
                ->line('One of your invoices has been paid!')
                ->action('View Invoice', $url)
                ->line('Thank you for using our application!');
}
 Result as below :



References :

https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/9
https://laravel.com/docs/5.4/notifications

Friday, 17 March 2017

Amazon Web Service (AWS)

Basically AWS is a secure cloud services platform, offering compute power, database storage, content delivery and other functionality to help business and technology growth.

Amazon Web Service also is comprehensive and evolving cloud computing platform provided by Amazon.com. Web Services are sometimes called cloud services.


What is Cloud Computing?

Cloud computing is a general term for the delivery of hosted services over the internet.
Cloud computing enables companies to consume a compute resource, such as a virtual machine (VMs), storage or an application, as a utility -- just like electricity -- rather than having to build and maintain computing infrastructures in house.

The services provided by the Amazon Web Service are :
  • CloudDrive - allow users to uplaod files, important documents , videos , music , photos from web-connected devices. The service also enable users to stream music to their database,
  • CloudSearch
  • Dynamo Database ( also known as Dynamo DB)
  • Elastic Compute Cloud
  • ElastiCache
  • Mechanical Turk
  • Redshift (Data Warehouse)
  • Simple Storage Service (S3)


Reference
http://whatis.techtarget.com/definition/Amazon-Web-Services-AWS

Thursday, 16 March 2017

Topic 10 - Explicit , Implicit & Restful Resource Controller

EXPLICIT CONTROLLER

In every laravel project explicit controller is very common routing that developer team use.
Explicit routing is pointing every action ( GET, POST) to a function of a controller. Explicit controller provide a clearer view function and routing name. Explicit controller was use to add additional method or method with specific naming convention.

Example of explicit controller that can be find in my project.

//return customer list
Route::get('customers', 'CustomerController@index');
//create customer form
Route::get('/create','CustomerController@showCustomerForm');

//store customer form
Route::post('/create','CustomerController@store');
IMPLICIT CONTROLLER (Deprecated)

Implicit controller is flexible because it allows you to easily define a single route to handle every action in a controller. You can define the route using the Route::controller method. The controller method accepts two arguments, first is URI the controller handles, while the second is the class name of the controller. 

According to laravel 5.0 documentation : 
If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:

public function getAdminProfile() {}

However implicit controller deprecated in Laravel 5.2. The call Route::controller was just added as an extra helper.

RESTFUL CONTROLLER

A restful controller can be found with some default routes and naming action .

Using syntax Route::resource('customers', 'CustomerController'); eventually will call default @index action which located in CustomerController. 

Actions Handled By Resource Controller

VerbURIActionRoute Name
GET/customerindexcustomer.index
GET/customer/createcreatecustomer.create
POST/customerstorecustomer.store
GET/customer/{customer}showcustomer.show
GET/customer/{customer}/editeditcustomer.edit
PUT/PATCH/customer/{customer}updatecustomer.update
DELETE/customer/{customer}destroycustomer.destroy
  
According to laravel  5.4 documentation HTML forms can't make PUTPATCH, or DELETE requests,  from here we neeed to add spoofing method in <form> tag. The method field can be define like below  :
{{ method_field('PUT') }}

Monday, 6 March 2017

Topic 9 - jQuery Datatables and Laravel

Topic 8 - Database Migration and Seeding

Migrations


Today we are going to learn to migrate to some of our database fields that we create inside database/migrations folder into or local database. Please follow these steps :

1: Php Artisan Command Migrate

php artisan make:migration alumnis



2: Migration Structure

class CreateAlumnisTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('alumnis', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('icno');
          $table->string('matrixno');
          $table->string('email');
          $table->timestamps();
          $table->softDeletes();
          $table->integer('created_by')->nullable();
          $table->integer('updated_by')->nullable();
          $table->integer('deleted_by')->nullable();
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
     public function down()
    {
        Schema::dropIfExists('alumni');
    }
}

3. Run Migration 

php artisan migrate 











4. Check Status Migrate

php artisan migrate:status














Seedings


However , after we migrate our migration file into our local database we cant leave them empty without example data. Seeding is more like initial data where we can insert dummies data to test with. Please follow these steps for better understanding :


1: Php Artisan Command Seeder


php artisan make:seeder AlumniSeeder
php artisan make:seeder -----> php artisan command
AlumniSeeder ----> table seeder



2: Class Seeder Structure


<?php

use Illuminate\Database\Seeder;

class AlumniSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      DB::table('alumnis')->insert([
           'name' => str_random(10),
           'icno' => str_random(10),
           'matrixno' => str_random(10),
           'email' => str_random(10),
       ]);
    }
}
3: Run Seeders File

By default , db:seed command runs all seeder files inside database/seeds folder. However we can specify seeder class by putting --class option to run individually.
php artisan db:seed
php artisan db:seed --class:AlumniSeeder


References 

https://laravel.com/docs/5.4/migrations#creating-tables
https://laravel.com/docs/5.4/seeding