Jun 16, 2018

How to add dummy data into table using Laravel seeder

Manually add data into the database it will take time and fussy for the redundant task. So this tedious job reducing by Laravel using seeder.

Let's check the demo of how to add dummy data in category table using Laravel seeder.

First, you need to install faker into Laravel. Faker is a PHP library that generates fake data for you

Install faker using composer command

composer require fzaninotto/faker

After installing faker you can see in require dev parameter in composer.json file in Laravel as below

composer.json file has below configuration:

"require-dev": {
        "fzaninotto/faker": "~1.4",
    },

For more information about faker, you can visit the links

Create categories seeder class using below command

php artisan make:seeder CategoriesTableSeeder

Run specific seeder using below command

php artisan db:seed --class=CategoriesTableSeeder

Refresh seeder class using below command with migrate.

php artisan migrate:refresh --seed

Categories Databse: CategoryID, CategoryName, Description - Here CategoryID is primary key

Category Model :
 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    public $timestamps=false;
}


I am adding 20 records as
1,category1, et sit et mollitia sed.
2,category2, et sit et mollitia sed.
etc into categories table.

 

use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CategoriesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
   DB::table('categories')->delete();
   
        $faker = Faker\Factory::create();
        for ($i = 1; $i < 20; $i++) {
            DB::table('categories')->insert([
                'CategoryName' => 'Category'.$i,'Description'=> $faker->text
        
            ]);
        }
  
    }
}

For the run, this CategoriesTableSeeder add this call into DatabaseSeeder class.
 
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
  $this->call(CategoriesTableSeeder::class);
    }
}

How to display category name in the product listing page using ORM in Laravel

Many developers facing the issue regarding category name display in the product listing page.

I also facing the same issue so I have figured it out using the relationship.

Can't display category name in Product List page because of category and product both are the different entity so both data stored into a different table

For that, need to give a relationship between product and category.

Let's see below example

The relationship between category and product:

A product belongs to category and category hasMany products.

My Database:

Category: CategoryID, CategoryName - Here CategoryID is primary key

Product: ProductID, CategoryID, Product Name, Image, Status, Created date - ProductID is Primary key and CategoryID is reference key

Product Model:
 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    
    public $timestamps=false; // default created_at and updated_at given so I passed as false;
    protected $fillable = [
        'category_id','product_name','image','status','created_date'
    ];
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

Category Model:
 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    public $timestamps=false;
    public function Product()
    {
        return $this->hasMany(Product::class);
    }

}
Once we have done with configuration model than see how to access category name in product listing template file.

Using below syntax it will display category name of that particular product.

{{$product->category->category_name}} -> Here category is relationship defined in product model.

create.blade.tpl
 

        @if(count($product) > 0 )
    @foreach ($product as $product)
     // You can access using category relationship in product model

        
    @endforeach
    @else
    
    @endif
    
    
    
Product Name Category Name Image Status Created Date
{{ $product->product_name}} {{$product->category->category_name}} @if ($product->status == '1') Active @else Inactive @endif {{ date('F d, Y', strtotime($product->created_date)) }}
No Record Found!!
Controller Code: How to fetch product data from the database and rendering create view.
 
public function create()
    {
        $product = Product::all(); 
        
        $params = [
            'title' => 'Product Listing',
            'product' => $product        ];

        return view('products.create')->with($params);
  
    }

May 13, 2018

How to load a component dynamically in Vue js

Going to learn one more topic about Vue Js. It's a component load dynamically in Vue Js.

Sometimes require component load based on some criteria or condition. That time needs to load component dynamically.

The above is made possible by Vue’s element with the is special attribute:
 




In the example above, currentTabComponent can contain either:

  1. the name of a registered component, or
  2. a component’s options object

Following are the full source code of the dynamic load component.
 






On the above code, we have two buttons one for Demo 1 and second for Demo 2 component.

Default Demo 1 component load and when press on Demo 2 button demo2 component load dynamically.

Click vice versa of Demo 1 and Demo 2 button and load appropriate component dynamically.

Hope you like the topic and useful to you.

Apr 7, 2018

Single Page Application using Asp.Net Core And Vue

How to create a single page application using asp.net core and Vue. Please watch the video for same.

I believe it's easy to create SPA with asp.net core and Vue.


Mar 31, 2018

ASP.NET Core 2.0 MVC View Components

Going to talk more about Asp.Net Core newly introduced feature of view components for reusable UI.

Introduction
It's similar to partial views, but it's very powerful to compare partial view. View components don't use model binding, and only depend on the data provided when calling into it

View Component has the following features.
  • Renders a chunk rather than a whole response.
  • It can have business logic as well as parameter
  • Is typically invoked from a layout page.
  • It also includes SOC (separation-of-concerns) and testability benefit
View Component represents in two parts.
1. View Component class typically derived from ViewComponent.
2. Return result as HTML typically a View.

The View Component class is similar to Controller class, it might have POCO.

A View Component class can be created in any of the following ways.

  • Class deriving from ViewComponent abstract class
  • Decorating a class with ViewComponent attribute or attribute that derived from ViewComponent attribute
  • Creating a class with suffix ViewComponent (like Controller class name)
Like controllers, view components must be public, non-nested, and non-abstract classes. This class fully supports constructor dependency injection. It does not take part in the controller lifecycle, which means you can't use filters in a view component

A view component defines its logic in an InvokeAsync method that returns an IViewComponentResult. Parameters come directly from the invocation of the view component, not from model binding. A view component never directly handles a request. Typically, a view component initializes a model and passes it to a view by calling the View method. Are not reachable directly as an HTTP endpoint, they must be invoked from your code (usually in a view). A view component never handles a request

Let's create a View Component class so it's easy to understand.

Creating a view component
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreViewComponent.Models;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreViewComponent.ViewComponents
{
    public class StudentListViewComponent : ViewComponent
    {
        public async Task InvokeAsync(int noOfStudent)
        {
            var students = new List();
            for (var i = 0; i <= noOfStudent; i++)
            {
                students.Add(new Student { Id = i, Name = "Student " + i.ToString() });
            }
            return View(students);
        }
    }
}

You can see a name of the class is StudentListViewComponent and it's inherited from the ViewComponent abstract class.

ViewComponent attribute can be used to change the name of the view component. For example, if we have the class named XYZ and want to set view component name to StudentList, this can be done using ViewComponent attribute.
 

[ViewComponent(Name = "StudentList")]
    public class XYZ : ViewComponent
    {
       ......       
       .......
        
    }

The runtime searches for the view in the following paths:

  • Views//Components//
  • Views/Shared/Components//
The default view name is "Default" for the view component. It means that our view name must be "Default.cshtml". We can assign a different name to the view of view component and this name must be passed to view method.

Invoking a view component
To use the view component, call the following inside a view:
 
@Component.InvokeAsync("Name of view component", "anonymous type") 
The parameters will be passed to the InvokeAsync method. The StudentList view component invoked from the Views/Students/Index.cshtml view file. In the following, the InvokeAsync method is called with two parameters:
 
@await Component.InvokeAsync("StudentList", new { noOfStudent = 4 })

Invoking a view component in View as a Tag Helper
Tag Helper was introduced in ASP.NET Core 1.1 and higher. For tag helper, Pascal case class and method parameter are translated into lower kebab case. We have to use "vc" element () to invoke the view component as a tag helper. It can be specified as follows.
 
  
    

Example
 
  
      

Note: In order to use a View Component as a Tag Helper, you must register the assembly containing the View Component using the @addTagHelper directive. For example, if your View Component is in an assembly called "ViewComponents", add the following directive to the _ViewImports.cshtml
file:
 
@addTagHelper *, ViewComponents

Invoking a view component directly from a controller
Mostly, view components are invoked from a view, but you can invoke them directly from a controller method. While view components don't define endpoints like controllers, so we can implement controller action that returns ViewComponentResult.

 
public IActionResult Index()
{
    return ViewComponent("StudentList", new { noOfStudent = 4});
}


Specifying a view name
The complex view component might require returning non-default view based on some condition. In the following example, ViewComponent will return StudentList view if the noOfStudent value is greater than 4.
 
public async Task InvokeAsync(int noOfStudent)  
{  
    var students = new List();  
    for (var i = 0; i <= noOfStudent; i++)  
    {  
        students.Add(new Student { Id = i, Name = "Student " + i.ToString() });  
    }  
    if (noOfStudent > 4)  
    {  
        return View("StudentList", students);  
    }  
    return View(students);  
} 

StudentList.cshtml view created from Default.cshtml view and its look like following code.
 
@model IEnumerable

Students

    @foreach (var student in Model) {
  • @student.Id - @student.Name
  • }

Output
Both the syntax used to generate out as well conditional render view also handle in this output.



Hope you like the new feature View Component of the Asp.Net Core. For source code you can visit my Github repo https://github.com/kalpeshsatasiya/AspNetCoreViewComponents

Mar 26, 2018

Vue Js Binding

Current market trends and very popular client-side frameworks are Angular, React and Vue.js.

Here we are talking about Vue.js and how the binding is working in Vue.js.

Please find sample tutorial of the Vue.js on my Github repo https://github.com/kalpeshsatasiya/VueTutorial

Also, I have recorded a video for Vue Js Binding feature and here you can watch it.
Hope you have enjoyed the video and Vue js tutorial.

Memory Cache in Asp.Net Core

The latest version of Microsoft Asp.Net has given the inbuilt feature of caching using Memory Cache.

Please find the example of Memory Cache in Asp.Net on my Github repo https://github.com/kalpeshsatasiya/MemoryCacheAspNetCore

Also, I have recorded the video for same and you can watch on my youtube channel.


Hope you enjoy the video and code sample.

Feb 25, 2018

HTML to PDF using Asp.Net MVC and Rotativa.AspNetCore

We are going to learn Rotativa.AspNetCore tool to use to generate PDF file from View.

Its very simple to create pdf using Rotativa.AspNetCore tool.

Prerequisite
1. Visual Studio 2017 with ASP.NET CORE 2.0
2. Rotativa.AspNetCore 1.0.6

Let's start with step by step.

1. Creating Asp.Net Core MVC application.

2. During the Asp.Net Core MVC project creation.


3. Once Asp.Net Core MVC application configuration done then we are ready to install Rotativa.AspNetCore to the project.

4. Install Rotativa.AspNetCore nuget package
 
Install-Package Rotativa.AspNetCore -Version 1.0.6



5. After installing NuGet package Rotativa.AspNetCore. Let's do some configuration on startup.cs class.

- Add this setting to a startup.cs class inside the configure method to set a relative path to the wkhtmltopdf.exe file to access.
 
RotativaConfiguration.Setup(env);



6. Time to add few exes under the "wwwroot\Rotativa" folder. Going to add following files to the "Rotativa" folder.
- wkhtmltopdf.exe
- wkhtmltoimage.exe



Once done with file adding. Let's move the final step.

7. We have Home Controller, so going to utilize that controller and use it.
An Index Action will be like this.
 

public IActionResult Index()
        {
            var customers = GetCustomers();
            return new ViewAsPdf("Index", customers);
        }

        private List GetCustomers()
        {
            return new List()
            {
                new Customer(){ Name="Kalpesh", City="Ahmedabad"},
                new Customer(){ Name="Vijay", City="Surat"},
                new Customer(){ Name="John", City="New York"},
                new Customer(){ Name="Smith", City="Parth"},
            };
        }


We are passing customer object into view. so we are getting an output pdf with the customer list.


You can do more configuration and get various output.

Download source code from my Github


Feb 15, 2018

How to create controller using artisan syntax in Laravel 5

We know, Laravel framework is current technology trend. I am facing the issue to create controller in laravel 5.

When I was following along with Learning Laravel 4 Application Development

I attempt to create my first controller with artisan by doing the following:

 
php artisan Usercontroller:make users
But when I did for Larvel 5 application controller, getting an error:
 
  [InvalidArgumentException]                                        
  There are no commands defined in the "Usercontroller" namespace.  

  Did you mean this?                                                
      controller 
What is happening here?

Because of above mention artisan use for the Larvel 4 and not for Larvel 5.

So there is the way in Laravel 4, but in Laravel 5 you should use it backwards php artisan

Solution for controller creation in Laravel 5.

 
php artisan make:controller Usercontroller

Hope it will help to you to controller creation in Laravel 5 application.

Vue.js Data Binding Syntax

We know, Vue.js is the hot topic as per the current technology trend. Trying to cover Vue.js data binding syntax with the example.

Vue.js uses a DOM-based templating implementation. This means that all Vue.js templates are essentially valid, parsable HTML enhanced with some special attributes.

Interpolations

1. Text
The most basic form of data binding is text interpolation using the “Mustache” syntax (double curly braces):

It a simple variable value display withing HTML.
 





Here msg is the property of data object. It will also be updated value whenever the data object's msg property changes.

You can also perform one-time interpolations that do not update on data change:
 
This will never change: {{* msg }}

2. Raw HTML
When we need to display real HTML then you will need to use triple mustaches because we have seen double mustaches use for plain text display.
 





using triple mustaches contents are inserted as plain HTML.

3. Attributes
Mustaches can also be used inside HTML attributes:

When required dynamic ids or any attributes that time attributes binding useful.
 




Note that attribute interpolations are disallowed in Vue.js directives and special attributes. Don’t worry, Vue.js will raise warnings for you when mustaches are used in wrong places.

Binding Expressions
The text we put inside mustache tags is called binding expressions. In Vue.js, a binding expression consists of a single JavaScript expression optionally followed by one or more filters.

1. JavaScript Expressions
We have seen simple property key binding so far. But Vue.js actually supports the full power of JavaScript expressions inside data bindings:

Make sure whatever inside the mustaches it's one single expression. so you can't declare the variable or flow control condition inside the mustaches.

Vue.js is smart to raise the error if you put something in the wrong place.
 




2. Filters
Vue.js support optional "filters". Append to the end of an expression, denoted by the “pipe” symbol:

Vue.js provides a number of built-in filters so we can pick one of if here.
 




Here we are “piping” the value of the message expression through the built-in capitalize filter

Directives
Directives are the special attributes with v- prefix. I think each client-side framework have directives.
Vue.js has also provided the same with v- prefix. Directive attribute values are expected to be binding expressions, so the rules about JavaScript expressions and filters mentioned above apply here as well. A directive’s job is to reactively apply special behavior to the DOM when the value of its expression changes.
 




Here, the v-if directive would remove/insert the element based on the truthiness of the value of the expression greeting.

1. Arguments
Some directives can take an “argument”, denoted by a colon after the directive name. For example, the v-bind directive is used to reactively update an HTML attribute:
 




Here href is the argument, which tells the v-bind directive to bind the element’s href attribute to the value of the expression url. You may have noticed this achieves the same result as an attribute interpolation using href="{{url}}": that is correct, and in fact, attribute interpolations are translated into v-bind bindings internally.

Shorthands
Vue.js provides special shorthands for two of the most often used directives, v-bind and v-on:

1. v-bind Shorthand
 




2. v-on Shorthand
 



Hope you like it. Next blog also be on Vue.js

Jan 21, 2018

Getting Started With Vue CLI with Vue Router

We know Vue is already a great Javascript library that allows you to create dynamic, front-end applications for single page application.

Single Page Application(SPA) is different then serve side application like asp.net or PHP.
Server-side application rending and routing different routes on the backend and getting a fully rendered page as a response.

For SPA page rending and routing on the front-end and only sends requests to the server when new data is needed or needs to be refreshed or saved.

So for SPA can improve the responsiveness of your web application because you can render the pages once and display them dynamically based on the current context of the application.

Routing and SPA fully supported in Vue. Vue has router library called vue-router. Now we are going to use Vue CLI command line installer to create a project.

Open a terminal and execute the following command.

 
# install vue-cli
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack my-project

Ref: https://vuejs.org/v2/guide/installation.html#CLI
Once you execute it will be prompted, answer the questions displayed on the screen like so. Make sure to answer "yes" for installing vue-router and other options.
Once the app is set up, install all the dependencies and start up a dev server.
 
# install dependencies and go!
$ cd my-project
$ npm install
$ npm run dev

Now you will see the application run on http://localhost:8080 browser. You will see the default layout provided by the vue cli.

Default its given HelloWord components in the application but we want to use the route for SPA application.

Going to create new components "First.vue" file under the components folder and add the reference on "index.js" file under the Route folder.



Refer above image with the highlighted section, have added First component routing for "/first" page.

Modified on App.vue page and added two links to navigating on HelloWorld and First component.

Following is the change in App.vue page.


For HelloWorld pointed to default page("/" ) and First pointed to "/first" page. Now we are set to navigate the pages for default to first and visa versa.

Basic routing is done here with Vue application. If you have a mark on the URL there is the # with URL. If you want to remove the # mark from the URL then you should do a modification of the mention routing file.

Add mode: 'history' on Router object.
 
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import First from '@/components/First'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/first',
      name: 'First',
      component: First
    }
  ]
})

Full source code on my Github
Hope you like and take advantage of Vue CLI.