Friday, May 3, 2019

Vue js : Vue Router Nested Routing tutorial

In this tutorial, we will learn about nested routing in vue router with the help of an example.

Nested Routing

Nested routing helps us to render sub-routes inside a particular route like user/1 or user/1/post.
In vue router normally we define one root <router-view> outlet where it renders the component which matches the defined path similarly, a rendered component can also contain it’s own, nested <router-view>.
Let’s create a User component with <router-view> outlet.
User.vue
<template>
  <div>
    <h1>User page</h1>
    <router-view></router-view>  </div>
</template>
To create a nested routing inside User component we need to add child routes in vue router constructor.
main.js
import Vue from 'vue'
import App from './App.vue';
import VueRouter from "vue-router";
import Home from './components/Home.vue';
import User from './components/User.vue';
import UserInfo from './components/UserInfo.vue';

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes: [
    { path: '/', component: Home },
    {
      path: '/user', component: User, children: [
          //UserInfo component is rendered when /user/:id is matched
        { path: ':id', component: UserInfo, props: true }      ]
    },
  ]
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
In the above code, we have added children array with nested routes in our Usercomponent.so that UserInfo component is rendered inside the User component when it matches user/:id.
Now inside UserInfo component we can access the dynamic segment id with props.
UserInfo.vue
<template>
  <div>
    <h2>User ID {{id}}</h2>
  </div>
</template>

<script>
export default {
  props: ["id"]};
</script>
Let’s update our User component by adding navigation for the nested routes.
User.vue
<template>
  <div>
    <h1>User page</h1>
    <strong>Select a user</strong>
    <ul class="nav">
      <router-link to="/user/1">User 1</router-link>      <router-link to="/user/2">User 2</router-link>      <router-link to="/user/3">User 3</router-link>    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
</script>

Vue : Vue History Mode Routing Tutorial

Vue History Mode Routing Tutorial. The default mode for the vue-router is hash(#) mode as it uses the URL hash to simulate a full URL so that the page won’t be reloaded when the URL changes.

To get rid of the hash mode, we can use the router’s history mode, which leverages the history.pushState API to achieve URL navigation without a page reload.

https://appdividend.com/2018/07/13/vue-history-mode-routing-tutorial/

Monday, April 29, 2019

Ajax : 5 best libraries for making AJAX calls in React

jQuery $.ajax

This is a quick & dirty way to make AJAX calls. In the former, official React tutorial, they use jQuery to fetch data from the server. If you are just starting out and are playing around with React, this can save you a lot of time. Many of us are already familiar with jQuery. So, it won't take a lot of time to understand and use it in React. Here is how a simple API call is made, with jQuery:
loadCommentsFromServer: function() {
      $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data}); // Notice this
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  }
P.S. Snippet is from React's former official tutorial.
It's the same old jQuery's $.ajax used inside a React component. Notice how this.setState() is called inside the success callback. This is how you update the state with data obtained from the API call.
However, jQuery is a big library with many functionalities - So, it doesn't make sense to use it just for making API calls (Unless you are already using it for a bunch of other tasks). So, what's the alternative? What should we use? The answer is fetch API.

Fetch API

Fetch is a new, simple and standardised API that aims to unify fetching across the web and replace XMLHttpRequest. It has a polyfill for older browsers and should be used in modern web apps. If you are making API calls in Node.js you should also check out node-fetch which brings fetch to Node.js.
Here is what the modified API call looks like :
loadCommentsFromServer: function() {
    fetch(this.props.url).then(function(response){
        // perform setState here
    });
}
In most modern React tutorials you will find fetch being used. To know more about fetch, check out the following links :

Superagent

Superagent is a light weight AJAX API library created for better readability and flexibility. If due to some reason, you don't want to use fetch, you should definitely check this out. Here is a snippet to demonstrate its usage :
loadCommentsFromServer: function() {
    request.get(this.props.url).end(function(err,res){
        // perform setState here
    });
}
Superagent also has a Node.js module with the same API. If you are building isomorphic apps using Node.js and React, you can bundle superagent using something like webpack and make it available on the client side. As the APIs for client and server are the same, no code change is required in order to make it work in the browser.

Axios

Axios is a promise based HTTP client for Node.js and browser. Like fetch and superagent, it can work on both client and server. It has many other useful features which you can find on their GitHub page.
Here is how you make an API call using Axios :
loadCommentsFromServer: function() {
    axios.get(this.props.url).then(function(response){
      // perform setState here
    }).catch(function(error){
      //Some error occurred
    });
}

Request

This list will be incomplete without request library which was designed with simplicity in mind. With more that 12k GitHub stars, it's also one of the most popular Node.js modules. You can find more about request module on their GitHub page.
Sample usage :
loadCommentsFromServer: function() {
    request(this.props.url, function(err, response, body){
          // perform setState here
    });
}



Sunday, April 21, 2019

Laravel : Laravel 5.6 - User Roles and Permissions (ACL) using Spatie Tutorial

ACL stands for Access Control List. ACL roles and permissions are very important if you are making big application in laravel 5.6. this tutorial will explain how to implement User Roles and Permissions(ACL) using spatie/laravel-permission composer package. So basically i will do it from scratch how to create permissions, roles, and users with assign roles etc.
I also posted on tutorial for ACL User Roles and Permissions using entrust package, you can see here : Laravel 5 - User Roles and Permissions (ACL) using entrust package.
If you are work on big ERP or Project then you need to control access to certain sections of the website. I mean you require to role permissions based access control database design that way you can specify the level of the user.
Roles and Permissions through you can create several types of users with different role and permission, i mean some user have only see a listing of items module, some user can also edit items modules, for delete and etc.
In this examples I created three modules as listed below:
User Management
Role Management
Product Management
After register user, you don't have any roles, so you can edit your details and assign admin role to you from User Management. After that you can create your own role with permission like role-list, role-create, role-edit, role-delete, product-list, product-create, product-edit, product-delete. you can check with assign new user and check that.
You need to just follow few step and you will get full example of ACL:



Creative code : PHP - Dynamically Add Remove input fields using JQuery Ajax Example with Demo

In this post, we will learn how to add and remove form input fields dynamically using jQuery and store in database using PHP. Here you will see how to handle dynamically added fields value save in mysql database using PHP Bootstrap. I will show you full example of dynamically add/remove input fields and submit to database with jquery ajax and php. you can also see add more fields jquery demo.
Few days ago i posted add/remove multiple input fields dynamically with jquery ajax in Laravel Framework, You can see here : Laravel - Dynamically Add or Remove input fields using JQuery.
We almost need to require add more functionality when client want to at time multiple value insert into database. It will great if you are use something interesting like give them input box with "+" button that way they can add multiple values at time.
So here you have to just follow few step to proceed.
1) Create Database Table
2) index.php File
3) addmore.php File
After Completed full example, you will get layout like as bellow:
Step 1: Create Database Table

In fist step, we need to create database and table, so here i created "test" database and "tagslist" table with id and name column. You can simply create "tagslist" table as following sql query.
SQL Query:
CREATE TABLE IF NOT EXISTS `tagslist` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24 ;
Step 2: Create index.php File
Here, we need to create index.php file and i created form with one input text box and button. I also write code for add more fields in jquery. So let's create index.php file and put bellow code.
index.php

<!DOCTYPE html>
<html>
<head>
<title>PHP - Dynamically Add or Remove input fields using JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 align="center">PHP - Dynamically Add or Remove input fields using JQuery</h2>
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required="" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "/addmore.php";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
alert('Record Inserted Successfully.');
}
});
});
});
</script>
</body>
</html>
Step 3: Create addmore.php File
In this step, we will write code of insert data into database using mysql query. So you have to create addmore.php and put bellow code:
addmore.php
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "root");
define (DB_DATABASE, "test");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if(!empty($_POST["name"])){
foreach ($_POST["name"] as $key => $value) {
$sql = "INSERT INTO tagslist(name) VALUES ('".$value."')";
$mysqli->query($sql);
}
echo json_encode(['success'=>'Names Inserted successfully.']);
}
?>