Friday, 30 December 2016

Sails vs Trails

Now a days so many frameworks are populating and some of them are gaining the interest from communities.So sails and trails are also a web framework so we start with basic introduction on both.

Sails vs Trails Node.js


TrailsJS : Trails is a modern, community-driven web application framework for node.js. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.


Creator: Travis Webb
GitHub: https://github.com/trailsjs/trails (1431+ stars) 
Age: 1+ year (release on 3rd Dec, 2015)
Support: Express4/5, Hapi, Koa, Restify
+1 Features: ES6, Trailpack, Footprint, Microservices
RealTime: Primus, Socket.io, Engine.io (Externally)
DB: MongoDB, MySql, Postgres, Redis, RethinkDB
ORM: Mongoose, Waterline, Knex & more…

SailsJS : Sails.js is a web framework that makes it easy to build custom, enterprise-grade Node.js apps.It is designed to resemble the MVC architecture from frameworks like Ruby on Rails, but with support for the more modern, data-oriented style of web app development. It's especially good for building realtime features like chat.


Creator: Mike McNeil
GitHub: https://github.com/balderdashy/sails (16k+ stars)     
Age: 4+ year (release on 25th Jun, 2012)
Support: Express3/4
+1 Features: Hooks, Blueprint
RealTime: Socket.io (Inbuilt)
DB: MongoDB, MySql, Postgres, Redis and more…
ORM: Waterline & other

Similarity in both :

Automatic REST APIs from models : Sails uses blueprint while Trails users footprints.

MVC : Both these frameworks are uses MVC pattern in default but with the trailsJS you can do a code with different pattern also. It supports multiple web framework & dynamic file loading.

Support web-sockets for real time : Sails comes with inbuilt socket.io supports like pub-sub & socket-client.In trails you don't have a directly support you can configure it manually.Some trailpacks for real-time support. trailpack-realtime & trailpack-pubsub.

Support multiple databases : Both supports almost all major databases like MongoDB, MySQL, Redis, CouchDB.


Plugin system : Trails has plugins system like trailpack & microservices.Sails comes with plugin system named Hook.

Policies & Services : Both using same architecture and usage for (http://sailsjs.com/documentation/concepts/policies)


How they are differ :

File loading : Sails loads all files under apis & config folders on start up (sails lift). It loads file at startup so it cause of all loading server slowly.So when your project size will be increased so startup time of server also increased. Trails will not loaded automatically. In trails every thing is loaded using index.js file so you can manage with that file.

ORM : Sails default orm is waterline. you can disbale it to use another one. Trails supports multiple ORM's like mongoose etc.

ECMAScript : Sails is built with ECMAScript 5. So It can run with Node ≥ 0.11 and Trails is built with ECMAScript15 (es6). So trails need node ≥ 4.0.

Web Server : Sails uses (built upon) Express3 (deprecated) as a web server so this will be main drawback of sails .Trails’s main advantage is It’s not built upon but built besides.

I hope you like the post please comment and share.




Tuesday, 20 December 2016

Architecture overview of Elasticsearch

If you are building an large application then you should definitely consider Elasticsearch for your datastore.Elasticsearch is not a good choice for the transaction processing system it is used for the search . We treat it as a search server and elasticsearch is built for speed and scalability. You should not be used elasticsearch for your primary data source because it may lose data.

Overview of elasticsearch



You can use elasticsearch for two reasons:

1. Real-Time analytics.
2. Powerful and Intelligent Search.

Elasticsearch is great for analytics applications:

  • Simple Super powerful Query DSL.
  • REST API for indexing data and querying it.
  • Easily configurable of shards and replicas.

Difference between elasticsearch and database.
In elasticsearch an index is like a database in which you can store different type of documents .Type of elastic is like a table in database , document you can call it a row and field in elasticsearch are coloumns in normal database.


Elasticsearch Relational Database
Index Database
Type Table
Document Row
Field Coloumn

Clusters and Nodes: Clusters are a collection of nodes that communicate with each other to read and write to an index. A cluster needs a unique name to prevent unnecessary nodes from joining and a node is single instance of ES usually it runs one instance per machine.It can communicate with network also so you can share it on network for reading and writing operations.



Shards and Indices: Let's take an example we have 1 TB machine it data is on it. If data is rapidlly increasing into machine then we might need a second machine to store some data. so data is divided into two machines which are in same cluster so we called it shards.

Replicas: Replicas are just shards that aren't actively used They're copies of your active shards to allow better availability should one of the nodes in your cluster fall down.

Please comment and share if you like the post.


Saturday, 17 December 2016

SQL vs NoSQL

SQL (Structured Query Language) databases have been a primary data storage mechanism for more than four decades and open source options are such as MySQL, PostgreSQL and SQLite.

SQL vs NoSql



  • The model is of a relational nature
  • Data is stored in tables
  • Suitable for solutions where every record is of the same kind and possesses the same properties
  • Adding a new property means you have to alter the whole schema
  • The schema is very strict
  • ACID transactions are supported
  • Scales well vertically
  • Good for structured data.



NoSQL databases have existed since the 1960s, but have gaining attraction with popular options such as MongoDB,Redis, CouchDB and Apache Cassandra.NoSQL databases that enable storing unstructured and heterogeneous data at scale have gained in popularity.

  • The model is non-relational
  • May be stored as JSON, key-value, etc. (depending on type of NoSQL database)
  • Not every record has to be of the same nature, making it very flexible
  • Add new properties to data without disturbing anything
  • No schema requirements to adhere to
  • Support for ACID transactions can vary depending on which NoSQL DB is used
  • Consistency can vary
  • Scales well horizontally
  • Good for semi structured,complex or nested data.

SQL Database : 

  • MySQL Community Edition
  • MS-SQL Server Express Edition
  • Oracle Express Edition


NoSQL Database :

  • MongoDB
  • CouchDB
  • Redis


Best Laravel package to use in your project

Start you laravel project and confuse for choosing a package stuff.I have made a list of some of the best laravel packages available to solve the same dilemma.The following packages listed below are mostly used and trusted also.

Best laravel library should be used for your project


Laracasts Flash: It's easy flash messages for your laravel app – Creator is Jeffrey Way so no second thought.

Eloquence: Extensions for the Eloquent ORM – Easy to implement and active developer.

Intervention Image: An open source php image handling and manipulation library – Great Documentation and active communtiy.

Entrust: It is role based permissions – Easy to implement.

PHP Vars To Js Transformer: Transform PHP types to JavaScript in the most easy way – Again , Jeffrey Way.

Medialibrary: Associate files with Eloquent models – Active developers and easy to use.

Log viewer: Your error logs at a single route – Neat UI.

JWT Auth: JSON Web Token Authentication for Laravel & Lumen.

Monday, 12 December 2016

Create components in vue.js

Vue : is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable.

Create Component in Vue.js


The easiest way to say hello to vue.js is using JSFIDDLE hello world example.


<input type="text" list="idOfDatalist" /> 
 <datalist id="idOfDatalist">
      <option value="element1" />
      <option value="element2" />
</datalist>

As you can see its composed of two elements, the datalist which containes the elements, and the input. isn’t a good example of use of component?

Template :

<template id="auto-complete">
 <input type="text" name="{{id}}" list="{{id}}" :style="styleObject" /> 
 <datalist id="{{id}}">
 <option v-for="framework in frameworks" value="{{framework}}" />
 </datalist>
</template>


In this we need to provide the id and the frameworks which is nothing but a an array.

Component:

Vue.component("auto-complete", {
    props : ['frameworks', 'id'],
    template : "#auto-complete",
})

the component method register a global compenent that can live outside the Vue Instance, we should provide its name and an object of options such as :

Template : which holds the id of the template that we declared before.

Props : its the list of options that will be used by the component, think of it as a box that holds the data sent by the outside world.

Now how to use it.

Declare a vue.js instance and provide a data to it.

new Vue({
 el: "#app",
data: {
    id: 'jsFrameworks',
    list: [
       'JQuery',
       'React',
       'VueJs',
       'AngularJs',
    ]
   }
})

And finally the component is :


<div id="app">
 <auto-complete :frameworks="list" :id="id"></auto-complete>
</div>

I Hope you like the post please comment and share.

Sunday, 11 December 2016

Laravel JWT auth with vue.js

This post is about laravel JSON Web Token based authentication using the new version of vue.js.The vue.js 2.0 has been released you can check here.

Laravel JWT auth with vue.js


Here i'm using laravel 5.2

Install some command line tools:

NPM version 3.10.8
Nodejs version 6.9.1
vue-cli version 2.5.0
git version 2.10.2

User Model : In laravel set your database connection in your .env file and run the migration for the create users , passwords resets etc.I have moved the Users class into a Models folder.


php artisan migrate

mkdir app/Models

mv app/User.php app/Models

Edit app/Models/User.php, change the App namespace to App\Models.

User.php


<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{

}


To view the full source please check the repo.

Edit, config/auth.php. Update the authentication drivers user provider for the App\Models\User namespace change as follows.

auth.php


'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    ...

You can read the full article here :

http://jimfrenette.com/2016/11/laravel-vuejs2-jwt-auth/?utm_source=wantcode.in

Thursday, 1 December 2016

Full-Text Search using Mysql

Search is very basic functionlity in website.Everyone wants a better search for their website so in this post i will show you how to create a full text search using mysql. All you need is mysql 4.X version or above.MySQL provides full text search capabilities that we can use to implement search functionality.

Full text search in mysql


CREATE TABLE post_articles (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    title VARCHAR(200),
    body TEXT,
    FULLTEXT (title,body)
);

Also add some sample data in this table. Execute following insert query.


INSERT INTO post_articles (title,body) VALUES
    ('MySQL Tutorial','DBMS stands for DataBase ...'),
    ('How To Use MySQL Well','After you went through a ...'),
    ('Optimizing MySQL','In this tutorial we will show ...'),
    ('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
    ('MySQL vs. YourSQL','In the following database comparison ...'),
    ('MySQL Security','When configured properly, MySQL ...');

Now natural language full text search like :


SELECT * FROM post_articles WHERE MATCH (title,body) AGAINST ('database');  

his query will search against word "database"  in title and body.

Boolean Full-Text Searches : sometime you want to specify certain keywords in your search criteria.
Also you may want to ignore certain keywords. Boolean Full-Text Search can used to perform a full text search for such requirements.


SELECT * FROM post_articles WHERE MATCH (title,body) AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);

This query will fetch all the records which has MySQL keyword but not YourSQL keyword. Notice the + and – that we have specified before the keywords!

+ stands for AND
– stands for NOT

Following are few examples for the boolean search criteria.

‘cricket football’
Find rows that contain at least one of the two words.

‘+cricket +football’
Find rows that contain both words.

‘+cricket hockey’
Find rows that contain the word “cricket”, but rank rows higher if they also contain “hockey”.

‘+cricket -hockey’
Find rows that contain the word “cricket” but not “hockey”.

I hope you like the post please comment and share.


Object Oriented Programming using JavaScript

JavaScript as the world’s most misunderstood language some programmers think that javascript language have lacks the common object-oriented programming concepts.But in this post i will show you how to write a class based javascript comes packed with a rich system of object-oriented programming that many programmers don’t know about.

object oriented programming using javascript


Prototype Based OOP : Conceptually, in class-based OOP, we first create a class to serve as a “blueprint” for objects, and then create objects based on this blueprint.For a real-world analogy, if you were to build a chair, you would first create a blueprint on paper and then manufacture chairs based on this blueprint. The blueprint here is the class, and chairs are the objects. If you wanted to build a rocking chair, you would take the blueprint, make some modifications, and manufacture rocking chairs using the new blueprint.

Lets create a new example of oops based prototype:


var student = Object.create(null);

Object.create(null) creates a new empty object.Now we add some properties and functions to our new object.


student.name = 'Peter';
student.gender = 'Male';
student.description = function() {
 return 'Gender: ' + this.gender + '; Name: ' + this.name;
};

Now student object can be used like:


console.log(student.description());
//Gender: Male; Name: Peter

We can create other, more specific student by using our sample object as a prototype.Think of this as cloning the object just like we took a chair and created a clone in the real world.


var stObj = Object.create(student);

We just created a stObj as a clone of the student. We can add properties and functions to this:


stObj.purr = function() {
 return 'Okay!';
};

We can use our stObj as a prototype and create a few more students:


var stObj1 = Object.create(stObj);
stObj1.name = 'Hello';

var stIbj2 = Object.create(stObj);
stIbj2.name = 'World';

console.log(stIbj2.description());

Class : How to write class based prototype in javascript let's see.


function Person() {
    //function Properties
    this.name = "Mac";
    this.age = "25";
    // start functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person();
alert(p.sayHi());

Constructor : Constructor is a concept that comes under Classes.The constructor is used to assign values to the properties of the Class while creating an object using the new operator.


function Person(name, age) {
    //Now assigning values through constructor
    this.name = name;
    this.age = age;
    //functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}

//Creating person instance
var p = new Person("mac", 25);
alert(p.sayHi());
//Creating Second person instance
var p = new Person("john", 23);
alert(p.sayHi());

Inheritance : Inheritance is a process of getting the properties and function of one class to other class. For example, let’s consider "Student" Class, here the Student also has the properties of name and age which have been used in Person class. 


function studentClass() {}
studentClass.prototype = new Person();
studentClass.prototype = Object.create(Person);
var stobj = new studentClass();
alert(stobj.sayHi());

I hope you like the post please comment and sha

Friday, 25 November 2016

Why people choose laravel framework

Laravel is one of the most popular PHP frameworks among the web artisans. Laravel is  the latest web app framework with this framework you can make web  development rapid and easy by by enabling general tasks that will be used in the majority of web projects such as queue, sessions, caching and authentication.

Why people choose laravel


It comes with a rich set of features. Using the resource controllers, CRUD process is very simple. The eloquent ORM helps in intracting with the databases. Every model developed in the MVC structure correlates to a table in the database.
Laravel have the expressive and elegant syntax that has been designed to ease and speed up the web development process. It has a vibrant developer community over the internet.


There are many reason behind for choosing the laravel framework because it incorporates established and proven web development patterns, MVC Application structure and Active record powering its database wrapper.It helps a developer to build a maintainable web application with easy to understand code separation in a short time frame.

Modular : Laravel is built on more than 20 different libraries and is itself split up into individual modules. It has adopted modern PHP principles which allow developers to build responsive, modular and user friendly apps.

Libraries : It supports many development environments and adjust itself based on the appropriate platform where app is running.

Template Engine : It is very lightweight templates with which you can create amazing layouts with dynamic content seeding. It has many widgets having JS and CSS code with solid structures.

Quickly : The PHP development companies have adopted Laravel due to its best dynamic capabilities to handle big web development projects.

Open Source : It is an open-source PHP web application framework, that makes easy and free process for building complex and large web applications with code maintainability.

Saturday, 19 November 2016

How to send mail using Node.js

In this post i  will show you how to send­ emails using G-Mail SMTP in Express(framework) Node.js.Sending a email using express js is pretty easy in node.js there are many library available for sending a mail.

Send mail using node.js express


Step 1: We are using express-mail libary for sending a mails and pugjs is a template engine which we are using for this post.

Step 2: Create a package.json file in your folder.


{
  "name": "send email using node.js",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: something going wrong\" && exit 1"
  },
  "keywords": [
    "express",
    "mailer"
  ],
  "author": "wantcode",
  "dependencies": {
    "express": "^4.14.0",
    "pug": "^2.0.0-beta6",
    "express-mailer": "^0.3.1"
  }
}

or you can directly genreate package.json using following commands.


npm init //initialize the npm 
npm install --save pug express express-mailer // install express mailer and pug dependencies

Step 3: Now come to main file called server.js.


// call the packages we need
const express = require('express');  // call express
const mailer = require('express-mailer'); // call express
const app = express(); // create a server
 
const port = process.env.PORT || 8000;  // set our port
 
// set the view folder to views
app.set('views', __dirname + '/template');
// set the view engine to pug
app.set('view engine', 'pug');
 
// Configure express-mail and setup default mail data.
mailer.extend(app, {
  from: 'info@wantcode.in',
  host: 'smtp.gmail.com', // hostname
  secureConnection: true, // use SSL
  port: 465, // port for secure SMTP
  transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts
  auth: {
  user: 'youremail@gmail.com', // gmail id
  pass: 'yourGmailPassword' // gmail password
  }
});
 
 
// test route to trigger emails
app.get('/', function (req, res) {
  // Setup email data.
  var mailOptions = {
    to: 'imsonujangra@gmail.com',
    subject: 'Email from SMTP sever',
    user: {  // data to view template, you can access as - user.name
      name: 'Sonu Jangra',
      message: 'Hello welcome to my website wantcode'
    }
  }
 
  // Send email.
  app.mailer.send('email', mailOptions, function (err, message) {
    if (err) {
      console.log(err);
      res.send('There was an error sending the email');
      return;
    }
    return res.send('Email has been sent!');
  });
 
});
 
app.listen(port, function () {
  console.log("Example app listening on port ${port}!");
});

Step 4: Create a view called template/email.pug.


doctype html
head
body
  div
   p
    b Hi #{user.name}
  div
    p #{user.message}

Step 5: Run the app using node app.js

Check the action on browser using  : http://localhost:8000/

Monday, 14 November 2016

Git ignore file permission changes

Sometime you change the mode of files of your project.

Git chmod



sudo chmod -R 777 /var/www/project

But files are not modified in the repo. check the modified files in git status. so git show all these files are modified.

So you can remove these files from modified using this command.


git config core.fileMode false


   core.fileMode
       If false, the executable bit differences between the index and the
       working copy are ignored; useful on broken filesystems like FAT.
       See git-update-index(1). True by default.

git -c core.fileMode=false diff

And the --global flag will make it be the default behavior for the logged in user.

git config --global core.fileMode false

I hope this post will help you.

ANDROID_HOME environment variable in ubuntu?

In this post i will show you how to set the ANDROID_HOME environment in ubuntu.Sometime after installing android studio you have noticed this issue of warning.

ANDROID_HOME environment



The ANDROID_HOME environment variable is not set or it points to a non-existent directory.
You will not be able to perform any build-related operations for Android.

So download the android and get the android download folder path like.

/home/wantcode/android

In this above line where wantcode is my system username and android is the folder where i downloaded android tools.So you can set the android path like.


export ANDROID_HOME=/home/wantcode/android/
export PATH=$PATH:$ANDROID_HOME:/home/wantcode/android/tools/
export PATH=$PATH:$ANDROID_HOME:/home/wantcode/android/platform-tools

After setting you can try to print the android path like.


echo $ANDROID_HOME


Sunday, 13 November 2016

Connect your mysql database with node.js

Node.js is popular framework today and real time things is possible with the node.js like real-time chat notification etc.So today i am going to show you how to connect node.js with mysql database.Node.js have a driver for MySQL that way we can easily connect with database and you can use select, insert, update and delete sql query.

Mysql Node.js


So lets start :

Step 1: Installed node.js if it is not installed in your system. 

sudo apt-get update
sudo apt-get install nodejs

You can read this post for installing the node.js from scratch

Step 2: Install npm for package management support.


sudo apt-get install npm

Now install the mysql package for node.js


sudo npm install mysql

I'm supposing you have installed php , mysql in your system and we are using node(database) if you don't have a database with name node then create it and inside it a users table .

Ok, so create new file server.js and put bellow code inside that file:

Step 3 : Ceate a new file.


var mysql      = require('mysql'); 

var connection = mysql.createConnection({ 
  host     : 'localhost', 
  user     : 'root', 
  password : 'root', 
  database : 'node' 
});

connection.connect(); 

connection.query('SELECT * FROM users', function(err, result, fields)  
{ 
  if (err) throw err; 

  console.log(result); 
}); 

connection.end();  

Now you have to run this file by following command:


nodejs server

This is very basic for mysql using node. you can explore node with the mysql here:

Laravel 5 mysql trigger from migration

Sometimes you need to add trigger in your mysql database of laravel 5.But how to create a trigger using laravel so laravel not provide special function like insertTrigger and something so it problem to create direclty, But laravel DB::unprepared() through we can create trigger for database.

Trigger in Laravel


So here i'm going to to show you how to create migration and create trigger code and how to write drop trigger code, so let's do it this way.


php artisan make:migration create_trigger

Create a Controller for trigger function :


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTrigger extends Migration
{
    public function up()
    {
        DB::unprepared('CREATE TRIGGER add_employees_salary AFTER INSERT ON `employees` FOR EACH ROW
                BEGIN
                   INSERT INTO `employees_salary` (`employee_id`) VALUES (NEW.id);
                END');
    }
    public function down()
    {
        DB::unprepared('DROP TRIGGER `add_employees_salary`');
    }
}


php artisan migrate

Saturday, 5 November 2016

Genreate a pdf using Laravel 5

In this tutorial i will show you how to export pdf or download using maatwebsite package. maatwebsite is a package which is used to genreate pdf file.you have a list of items in tables data you can download it in pdf formate.So lets start how to export or genreate a pdf.

Laravel 5 PDF


Step 1 : Add a new package in your composer.json file.


"maatwebsite/excel": "~2.1.0"

Then, run command composer update.

Step 2 : Now open config/app.php file and add service provider and aliase.


'providers' => [
 'Maatwebsite\Excel\ExcelServiceProvider',
],
'aliases' => [
 'Excel' => 'Maatwebsite\Excel\Facades\Excel',
],

Then run this command and this command is genreate config file for excel package.


php artisan vendor:publish

Step 3 : Also add dompdf package to download the pdf format.


composer require dompdf/dompdf

Step 4 : You have to create some migration command.


php artisan make:migration create_items_table

After this command you will find a file in path database/migrations and add this code to your migration file.


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration
{
   public function up()
   {
       Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->text('description');
           $table->timestamps();
       });
   }
   public function down()
   {
       Schema::drop("items");
   }
}

After creating the item table now you need to create a model in app/Item.php .


<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
   public $fillable = ['title','description'];
}

Step 5 :  Create Route and Controller in your app/Http/routes.php file.


Route::get('genreatepdf', 'ExportController@export');

Create a controller in path app/Http/Controllers/ExportController.php and put the below code.


<?php

use Input;
use App\Item;
use Excel;
class ExportController extends Controller
{
 public function export()
 {
    $data = Item::get()->toArray();
    return Excel::create('wantcode', function($excel) use ($data) {
  $excel->sheet('sheet1', function($sheet) use ($data)
     {
   $sheet->fromArray($data);
     });
    })->download("pdf");
 }
}

In this controller you just simply get the items array and pass to the excel function and download as PDF.

How to upload image in Laravel 5

Laravel the amazing framework of php which is most popular now.Today i want to share a post how to upload image in larvael 5.Laravel 5 provide very simple way to upload your image with validation like max size of 2MB, valid file extension like png,jpeg,gif,jpg or svg etc. You can easily implement in your application.

Laravel5


Step 1: You can make a simple route for uploading an image.Then first need to genreate view and second one is for post method.


Route::get('upload-image','ImageController@imageUpload');
Route::post('upload-image','ImageController@imageUploadPost');

Step 2: Now you need to create a controller named ImageController and create a images folder and check the permission of uploading an image. we will store the image in public/images folder.

app/Http/Controllers/ImageController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class ImageController extends Controller
{

    /**
    * Create view file
    */
    public function imageUpload()
    {
     return view('image-upload');
    }

    /**
    * Manage Post Request
    */
    public function imageUploadPost(Request $request)
    {
     $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);

     return back()
      ->with('success','Image Uploaded successfully.')
      ->with('path',$imageName);
    }

}

Step 3: Create a view file for uploading an image.


@if (count($errors) > 0)
<div class="alert alert-danger">
   <strong>Oops!</strong> There were some problems with your input.<br><br>
   <ul>
      @foreach ($errors->all() as $error)
      <li>{{ $error }}</li>
      @endforeach
   </ul>
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
   <button type="button" class="close" data-dismiss="alert">×</button>
   <strong>{{ $message }}</strong>
</div>
<img src="/images/{{ Session::get('path') }}">
@endif
<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
   {{ csrf_field() }}
   <div class="row">
      <div class="col-md-12">
         <input type="file" name="image" />
      </div>
      <div class="col-md-12">
         <button type="submit" class="btn btn-success">Upload</button>
      </div>
   </div>
</form>

Hope you like the post please comment below for the help.

Monday, 31 October 2016

Google Golang for Beginners

Computer programming is the art, craft and science of writing programs which define how computers operate.So in this post i will show you how to start programming with Golang (by google).Go is a general purpose programming language with advanced features and a clean syntax. Because of its wide availability on a variety of platforms, its robust well documented common library, and its focus on good software engineering principles, Go is an ideal language to learn as your first programming language.

Go lang : wantcode.in


Features of language Go :

Interfaces to replace virtual inheritance.
Syntax and environment adopting patterns.
Compiled into statically linked native binaries without external dependencies.
Remote package management.
Online package documentation.
Built-in concurrency primitives.
Large built-in library.
Type embedding to replace non-virtual inheritance.
Simple language specifications.
Fast compilation time.
Light testing framework.

How to install go lang in ubuntu : 

Step 1 : Open your terminal

curl -O https://storage.googleapis.com/golang/go1.6.linux-amd64.tar.gz

Next, you can use sha256sum to verify the tarball:


sha256sum go1.6.linux-amd64.tar.gz

Step 2 : Extract the tar.

tar xvf go1.6.linux-amd64.tar.gz

Step 3 : Permission change for go.

sudo chown -R root:root ./go
sudo mv go /usr/local

Step 4 : Set Go's root value which tells go where to look for its files.

sudo nano ~/.profile

Add these lines at the end of file


export GOPATH=$HOME/work
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin

After save the file close the file and refresh your profile by using command .

source ~/.profile

Step 5 : Create a simple hello program for go.

nano ~/work/src/hello.go

import the package for go 

package main

import "fmt"

func main() {
    fmt.Printf("hello world for go\n")
}

Save and close the file then compile it by invoking the Go command install:

go install ~/work/src/hello

With the file compiled you can run it by simply executing the command:


hello

if this will return hello world for go , that means successfully installed the lang go. This is just the begining steps to install go lang . I hope you enjoy the post please share and comment.

Saturday, 29 October 2016

Awesome date functions PHP

Dates are always an important part of any website but sometime it's very difficult to deal with, especially for beginners. So here is a list of a few some important php functions and code snippets that will definitely help you dealing with dates.

Php Date


Get Current time :
It's basic function takes no parameters and returns the current date. This example uses British date formatting, you can change it on line 2.


function nowDateInUk(){
 return date('d/m/Y', time());
}

Format A Date :
The simple way to convert a date from a format (yyyy-mm-dd) to another.For more extensive conversions, you should have a look at the DateTime class to parse & format.


$originalDateNow = "2016-10-29";
$newDateNow = date("d-m-Y", strtotime($originalDateNow));

Convert minutes to hours and minutes :
This is a super useful function for displaying times. Give it minutes as an integer (let's say 135) and the function will return 02:15.


function cnvToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

Get A week Number from date :
Sometime you need to find the week number of a particular date. Pass your date as a parameter to this function, and it will return you the week number.


function findWeekNumber($ndate){
 $res = new DateTime($ndate);
 return $res->format("W");
}

Difference between two dates:
This function takes two dates and returns the interval between two dates. The result is set to be displayed in hours and minutes.


function getDateDiff($date1, $date2){
     $datetime1 = new DateTime($date1);
 $datetime2 = new DateTime($date2);
 $interval = $datetime1->diff($datetime2);
 return $interval->format('%H:%I');
}

Check date is past or future :
Sometime you need to check that date which you are using is past date and future. So these functions will help you.


if(strtotime($dateString) > time()) {
     # your date is in the future
}

if(strtotime($dateString) < time()) {
     # your date is in the past
}

if(strtotime($dateString) == time()) {
     # your date is right now
}

Calculate age from date :
Very useful on websites where you need to check that a person is over a certain age to create an account.


function getAge($date){
    $time = strtotime($date);
    if($time === false){
      return '';
    }
    $year_diff = '';
    $date = date('Y-m-d', $time);
    list($year,$month,$day) = explode('-',$date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ($day_diff < 0 || $month_diff < 0) $year_diff-;
 
    return $year_diff;
}

I hope you like the post . If you like please share.

Wednesday, 26 October 2016

Some time saving commands of vim

Vim is an advanced text editor that seeks to provide the power of the de-facto Unix editor 'Vi', with a more complete feature set.  Since the 1970’s, Vi and Vim are popular amongst developers and are present on most UNIX-based servers.

Vim Editor


I'm showing you some good shorthand codes of vim it will charge your coding speed.

Some Basics Vim:

:e filename Open filename for edition
:w Save file
:q Exit Vim
:q! Quit without saving
:x Write file (if changes has been made) and exit
:sav filename Saves file as filename
. Repeats the last change made in normal mode
5. Repeats 5 times the last change made in normal mode

Some Moving file operations:

k or Up Arrow move the cursor up one line
j or Down Arrow move the cursor down one line
e move the cursor to the end of the word
b move the cursor to the begining of the word
0 move the cursor to the begining of the line
G move the cursor to the end of the file
gg move the cursor to the begining of the file
L move the cursor to the bottom of the screen
:59 move cursor to line 59. Replace 59 by the desired line number.
20| move cursor to column 20.
% Move cursor to matching parenthesis
[[ Jump to function start
[{ Jump to block start

Some Cut Copy Commands:

dd Cut current line
yw Yank word
y Copy the selected text to clipboard
yy Copy current line
y$ Copy to end of line
p Paste clipboard contents
D Cut to end of line

Some Search cheat sheet:

/word Search word from top to bottom
?word Search word from bottom to top
* Search the word under cursor
/\< ¦.\> Search all words of 4 letters
/\cstring Search STRING or string, case insensitive
/jo[ha]n Search john or joan
/\< the Search the, theatre or then
/\< the\> Search the
/\<\d\d\d\d\> Search exactly 4 digits
/^\n\{3} Find 3 empty lines
/the\> Search the or breathe
/\/ Search fred but not alfred or frederick
/fred\|joe Search fred or joe
:bufdo /searchstr/ Search in all open files
bufdo %s/something/somethingelse/g Search something in all the open buffers and replace it with somethingelse

Replace Commands :

:%s/old/new/g Replace all occurences of old by new in file
:%s/onward/forward/gi Replace onward by forward, case unsensitive
:%s/old/new/gc Replace all occurences with confirmation
:%s/onward/forward/gi Replace onward by forward, case unsensitive
:%s/ *$//g Delete all white spaces
:2,35s/old/new/g Replace all occurences between lines 2 and 35
:5,$s/old/new/g Replace all occurences from line 5 to EOF
:%s/^/hello/g Replace the begining of each line by hello
:%s/$/Harry/g Replace the end of each line by Harry
:%s/\r/\r/g Transform DOS carriage returns in returns
:%s#<[^>]\+>##g Delete HTML tags but keeps text
:g/string/d Delete all lines containing string
:v/string/d Delete all lines containing which didn’t contain string
:s/Bill/Steve/ Replace the first occurence of Bill by Steve in current line
:s/Bill/Steve/g Replace Bill by Steve in current line
:%s/^\(.*\)\n\1$/\1/ Delete lines which appears twice
Ctrl+a Increment number under the cursor
:%s/Bill/Steve/g Replace Bill by Steve in all the file
:%s/^M//g Delete DOS carriage returns (^M)
Ctrl+x Decrement number under cursor
ggVGg? Change text to Rot13

Read Write cheat:

:r infile Insert the content of infile
:1,10 w outfile Saves lines 1 to 10 in outfile
:1,10 w >> outfile Appends lines 1 to 10 to outfile
:23r infile Insert the content of infile under line 23

Explorer file:

:browse e Graphical file explorer
:ls List buffers
:e . Open integrated file explorer
:cd .. Move to parent directory
:args List files
:Sex Split window and open integrated file explorer
:Sex! Same as :Sex but split window vertically
:args *.php Open file list
:grep expression *.php Returns a list of .php files contening expression
gf Open file name under cursor

Syntax highlighting :


:syntax off Turn off syntax highlighting
:syntax on Turn on syntax highlighting
:set syntax=perl Force syntax highlighting

I hope you like the post please share and comment.

Monday, 24 October 2016

Create your first widget in Yii2

In this tutorial i will show you how you can create own custom widget in Yii2.The main advantage of Widget is you can write once and reuse it wherever you need it in your view. Widgets are reusable blocks and they are used in your views. Create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() or run() methods of base widget.

Yii2 Widget


Step 1: Create a folder named components or changed name in your project folder.

Step 2: Create a file with desired widget name inside components folder and paste the below code. Example – HelloWidget.php


<?php

namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class Hellowidget extends Widget
{

    public $msg;

    public function init()
    {
        
        parent::init();

        if ($this->msg === null) {
            $this->msg = 'Welcome Here';
        } else {
            $this->msg = 'Welcome ' . $this->msg;
        }
    }

    public function run()
    {
        // you can load & return the view or you can return the output variable
        return $this->render('my-widge', ['message' => $this->msg]);
    }
}

In HelloWidget is a class and we can access the widget like 'app\components\HelloWidget'.

Step 3: Create a view and put the content into it.

Step 4: Everything is done.you can call now widget.


<?php echo \app\components\HelloWidget::widget() ?>

I hope you like the post. please share and comment.

Saturday, 15 October 2016

How to create a webpage screenshot with NodeJs and PhantomJS

To create webpage screenshots we are using PhantomJs. PhantomJS is a headless WebKit scriptable with a JavaScript API. It has very fast and native support for various web standards like DOM handling, CSS selector, JSON, Canvas, and SVG. In simple words PhantomJS is a web browser without a graphical user interface.Assuming you already downloaded and installed PhatomJS, create a JavaScript file (capturescreen.js) with the following contents.

Phantom



var wpage = require('webpage').create();

wpage.open('http://wantcode.in/', function() {
    wpage.render('wantcode.png');
    phantom.exit();
});

Then you need to run this script in browser it won't work. you need to run in command line.


phantomjs capturescreen.js

After running this see in the same folder a png file is create of screenshot.For more option you can read the phantomJs here.Please feel free to comment below for suggestions and problems.

How to serve static files with node.js

In front end development to serve static files such as images, CSS files, and JavaScript files you require the web servers. and you need a server like apache or nginx servers to server files.Installing http server and configuration is much hactic for a frontend developers.With the help of node.js we can easily create a http web server.if you are using node.js environment then there is quick configuration package for HTTP server without writing a single line of code.

Node.js


Assuming you have Node.js installed in your machine.If node.js not installed please read this article Getting started with node.js. You need to install the module called http-server using the following command.


npm install -g http-server

That’s it. Now you can serve any static files and assets using this module. Now you switch to any folder and run the server using the following command and your folder will act as server and it will serve static files such as images, CSS files, and JavaScript files.


~/Desktop mkdir assets && cd $_
~/Desktop/assets http-server

Now assets folder will act like root of the Http server.Please feel free to comment below for suggestions and problems.



Pagination in laravel 5

Laravel provides pagination for Eloquent results which comes out of the box features but for custom data set we need to create paging.i'm using laravel5 LengthAwarePaginator class to show you how to create a pagination from a array of data.

Laravel Pagination


Step 1: Controller – app/Http/Controller/RecordsController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests;

class RecordsController extends Controller
{

    public function items(Request $request)
    {
        $items = [
            'item1',
            'item2',
            'item3',
            'item4',
            'item5',
            'item6',
            'item7',
            'item8',
            'item9',
            'item10'
        ];

        // Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();

        // Create a new Laravel collection from the array data
        $itemCollection = collect($items);

        // Define how many items we want to be visible in each page
        $perPage = 1;

        // Slice the collection to get the items to display in current page
        $currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

        // Create our paginator and pass it to the view
        $paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);

        // set url path for generted links
        $paginatedItems->setPath($request->url());

        return view('records_view', ['records' => $paginatedItems]);
    }
}

Step 2: View (resources/views/records_view.blade.php) file should look like this.


<h1>Records List</h1>
 
<ul>
@foreach ($records as $record) 
   <li> {{ $record }} </li>
@endforeach
</ul>
 
<div>
{{ $records->links() }}
</div>

Step 3: Now comes to the routing app/Http/Routes.php.


Route::get('records','RecordsController@records');

Please feel free to comment below for suggestions and problems.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts