InfyOm Blog

latest-post

In this article, I show you an easy way to set up browser push notifications. fist of all, you have a question what is push notification? let me explain a bit more. Push notification is the fastest way to get up and running with Javascript desktop notifications. Push notifications are messages that can be sent directly to a user's Desktop via browser.

You can watch the following tutorial and you can continue reading this article.

Follow the Steps given here for setup push notification.

Step 1: You can quickly install Push via npm

npm install push.js --save

Step 2: Update webpack.mix.js

Add following code into webpack.mix.js for copy and publish assets like js in the public directory. you can see the example here

mix.copy('node_modules/push.js/bin/push.min.js',
    'public/assets/js/push.min.js');

I hope you know how to use laravel mix. you can watch this video tutorial if you want to know more about the laravel mix.

fire, npm run dev command and publish js.

Step 3: Add assets in blade file

Add script before closing body tag.

Step 4: Add this code where you want to show a push

// add logo in public dir and use it here
const iconPath = '{{ asset('logo.PNG') }}
 Push.create("Hello Shailesh!",{
       body: "Welcome to the Dashboard.",
       timeout: 5000,
       icon: iconPath
});
December 03, 20213 MinutesuserShailesh Ladumor

Posts

post

Last month we started working on one of our internal project called InfyTracker, which we were planning to use as a simple time tracker and very little of project management or task reporting.

We have also published it as an open source project to our Github account so other people from the community can use it. It's still in alpha stage and we are still working on it and making tons of improvements. But, While building this project, we found a few things that we think might be useful to optimize the app or can be used in other projects. Also, I think lots of developers even do not realize these things.

So I planned to share it with the community where I will be discussing them in a detail with solutions we used. So here are the things/mistakes that we found during our project development.

  1. Adding all stylesheets and scripts in a layout file
  2. Not separating out page level CSS or JS
  3. Not using laravel-mix

1. Adding all stylesheets and scripts in layout

What I've seen is, when we want to add a new library/package to the project, people generally go to the layout file and just insert a style and script tag there.

For e.g., I want to use moment-js in the app, so what I do, I go to my layout file and include moment-js script tag there via CDN. Even if I only need moment-js in few of my pages. same can be there for other libraries like datatables, even if we only need datatables in a few pages of the app.

The problem it creates is, even if we don't need them in most of our pages, those files are still included in our page and of course, the page takes more time to load.

2. Not separating out page level CSS or JS

Generally, we use lots of JS in our code. And for all page level JS/CSS, most of the developers put it in a blade file of the page at the bottom with some section of JS/CSS.

For e.g, I have used a datatable in my page, so I need to initialize the datatable. so generally, I will have declared one section called scripts or bottom_js which will be yielded in my layout file. That's what I have seen in lots of code.

But, there are two problems with that,

  1. When that page is loaded, your JS code is completely visible to the world and sometimes that's not good and secure
  2. It's not minified (and since it's sitting into your blade files, there is no way to minify it either)

3. Not using laravel-mix

In really few projects or very few expert developers use laravel-mix or use laravel-mix in the right way. When you do not use laravel-mix in your site, your JS/CSS files are not minified. It's completely visible to the world which can be sometimes dangerous and file sizes are big as well in large projects.

That's the three major things that we found while developing this project.

Here is the solution that we used to overcome these problems.

Solution 1. Adding all stylesheets and scripts in specific pages

To resolve this problem, we declared two sections in our layout file.

  1. stylesheets
  2. scripts

so all of our web pages which has a dependency for the third-party CSS/JS libraries will look like following,

@extends('layouts.app') 
@section('stylesheets')     
<link rel="stylesheet" href="https://rawgit.com/fronteed/iCheck/1.x/skins/all.css">
@endsection 

@section('content')     
....content here.... 
@endsection 

@section('scripts')     
<script src="https://cdnjs.cloudflare.com/ajax/libs/iCheck/1.0.2/icheck.min.js"></script>
@endsection

As per the above example, the iCheck library will be only added on pages where we are actually using iCheck instead of all of my web pages.

Solution 2. Separating out page level CSS or JS

To resolve this problem, we also declared two new sections in the layout file.

  1. page_css
  2. page_js

page_css section will contain page level CSS and page_js section will contain page level javascript like initializing datatable or checkboxes etc. Also, all page level CSS and JS are not placed directly inside the blade file. But we go one step further.

Under the resources/assets folder, we have two folders,

  1. js - contains all page level JS for different blade files
  2. styles - contains all page level CSS for different blade files

We tried to follow the same folder structure for this that we used for our blade views.

Folder Structure

If you have multiple files then you can try to use names like index.js, edit.js, etc, just the same as your blade view names.

And in your blade view files, you can include them as a script or stylesheet. For e.g.

@section('page_js')     
<script src="{{ mix('assets/js/task/task.js') }}"></script>
@endsection

Note: Use of mix is explained in the next section. so you can just ignore that as of now. But the basic idea is, include them as a script or stylesheet with sections, instead of directly putting them in blade files.

Solution 3. Using laravel-mix

Laravel mix is a great tool for asset compilation. All of the page level JS/CSS files and other common JS/CSS should be compiled by laravel mix and should be copied to the public folder with versioning for cache busting. And then it will be included via mix helper in our blade views. (As explained in the above solution at the bottom of the section).

For e.g. our webpack.mix.js looks like the following,

/* CSS */ 
mix.sass('resources/assets/style/sass/laravel/app.scss', 'public/assets/style/css/app.css') 
.sass('resources/assets/style/sass/style.scss','public/assets/style/css/style.css') 
.sass('resources/assets/style/sass/dashboard.scss','public/assets/style/css/dashboard.css')
.version(); 

/* JS */ 
mix.js('resources/assets/js/custom.js','public/assets/js/custom.js') 
.js('resources/assets/js/users/user.js','public/assets/js/users/user.js') 
.js('resources/assets/js/task/task.js','public/assets/js/task/task.js')    
.version();

This will minify our code and make it secure in the production environment.

Hope this helps.

June 19, 20195 minutesauthorMitul Golakiya
post

Lots of people asked a question on our Github Repo about how they can display relationship data into index while using Datatables. so I decided to write a post with a detailed tutorial on that. Let's see how it's possible.

Problem:

Let's imagine the following simple scenario. We have a users table and we have a posts table. Post table is pretty simple with the following fields:

  • id
  • author_id
  • title
  • body
  • created_at
  • updated_at

Where author_id is a foreign key to the users table. We want to display the author name into the index table.

But since we need that data from the relationship, there is no direct way to display that into Datatable.

Solution:

Let's perform the following steps (before performing these steps, generate your CRUD with datatables for Post model):

Step 1: Add author relationship into Post model

Since we want to display the author name of the post, let's add author relationship into Post.php

public function author() {     
return $this->belongsTo(User::class, 'author_id'); 
}

Step 2: Modify PostDataTable

Since we have to display relationship data we need to load it using eager loading of laravel. Modify the query method of PostDataTable.php. something like,

public function query(Post $model) {     
return $model->newQuery()->with(['author']); 
}

Also, we need to add one more column author name into the datatable. so modify getColumns method and add that to the array. something like,

protected function getColumns() {     
return [        
       'title',         
       'author_name' => new \Yajra\DataTables\Html\Column([
       'title' => 'Author Name', 
       'data' => 'author.name',
       'name' => 'author.name'
      ])     
  ]; 
}

This will add one more column with header "Author Name" in the datatable before "Action" column. Here, we are adding custom datatable column where key will the name of column which datatable use internally, title will be used for Datatable Column header title and data will be used for retrieving data.

And that's it. Run your code and you should be able to see Author name of the post into your datatable.

March 19, 20192 minutesauthorMitul Golakiya
post

InfyOm Laravel Generator comes with two possible choices for a table in the index view.

  1. Native table with blade
  2. Datatables

Datatables comes with a huge set of features if you really need it and InfyOm Generator is capable of generating your CRUD table with Datatables. It uses yajra/laravel-datatables-oracle for that. But I heard from lots of people that they got confused about the installation of that package and how to use it with Generator. so I decided to write a post on that.

Yajra datatables come with a few different packages, one for core datatables and other plugins like buttons, HTML, export CSV etc. When you are using it with InfyOm Generator, you will need all of them since we generate a table with a full set of features.

Perform the following steps.

Step 1: Add Packages

In the first step, we need to add these packages into our project based on the laravel version we are using. Check the following table:

Laravel Version yajra/laravel-datatables-oracle yajra/laravel-datatables-buttons

yajra/laravel-datatables-html

5.5 8.x 4.x 4.x
5.6 8.x 4.x 4.x
5.7 8.x 4.x 4.x
5.8 9.x 4.x 4.x

Based on your laravel version, install these packages and add the following service providers and facade in config/app.php.

/** Service Providers **/  Yajra\Datatables\DatatablesServiceProvider::class, 
Yajra\Datatables\ButtonsServiceProvider::class, 
Yajra\Datatables\HtmlServiceProvider::class, 
/** Facade **/ 
'Datatables' => Yajra\Datatables\Facades\Datatables::class,  

Step 2: Run Vendor Publish

Once you add this, publish the assets for all these service providers. This is also one critical step. Make sure you run a vendor:publish for all these service providers. Or you can just run php artisan vendor:publish and select the service provider from the list and do this for all of these three service providers. It will publish some assets into your public directory.

Step 3: Enable Datatable option for Generator

After publishing assets, go to config/infyom/laravel_generator.php and make add_on => datatables => true.

Step 4: Scripts and CSS section into blade layout (Optional)

If you have used publish layout option then you can skip this step. Otherwise, make sure you have scripts and CSS sections into your main blade layout file. Since that's where all scripts and CSS will be added for datatables.

And that's it. Try to generate CRUD for some model and it should generate your crud with Datatables.

March 15, 20192 minutesauthorMitul Golakiya
post

Introducing Laravel 5.8 support to InfyOm Laravel Generator with more cleaner Repository Pattern

Laravel 5.8 just released this week with a bunch of new improvements. You can read the full post here about new updates. so in a very small fraction of time, we also worked on adding support for Laravel 5.8 into our generator. You can read the installation steps here.

Also, one another feature or improvement we have done is, we tried to create a cleaner and extendable repository pattern while generating CRUD. so far we were using prettus/l5-repository package, which is really awesome if you do not want to write your general functions of create/all/update/delete/find in all of your repositories. I really loved that package and that's the reason we extended that package when we created our repository.

This is all great when you are talking about simple CRUD functions. But things get confusing when people want to customize their code. I got a lot of emails and also lots of people created issues on Github regarding how to customize that function based on their certain needs.

So with this version, I decided to write our own simple BaseRepository which will be published into app/Repositories/BaseRepository.php. so developers are free to customize all the basic functions.

Actually, this is also possible with prettus/l5-repository as well and with our generator as well by publishing templates. But that needs some more work and some deep knowledge of customizing templates. But with this update, it will be easier.

Right now, I do not expect any breaking changes who are migrating their code from 5.7 to 5.8 which is using a generator. I tried to keep all old BaseRepository classes and repository packages into dependencies. All their existing generated repositories should work fine.

Still, if someone is getting any errors then they can contact me by creating issues on Github. I will try to respond there.

Hope this release will help and people can start to get started to upgrade their code to Laravel 5.8.

March 02, 20192 minutesauthorMitul Golakiya
post

We used Amazon SNS into one of our project where we need to receive instant updates to the various different microservices from other microservices. I was not able to find any good article which highlights everything about SNS integration into PHP or Laravel. This can be most confusing who is working with SNS for the first time. so I decided to write one which can help others. Following things are really important before we get started.

  • What exactly SNS is?
  • Where/When you can use it?
  • How does it work?
  • How to integrate it with PHP?

I will try to explain in a little bit brief here about SNS and will focus more on integration and problem that we tried to solve.

1. What exactly AWS SNS is?

AWS SNS stands for Amazon Simple Notification Service. It's a distributed pub/sub messaging system for microservices. Where publishers can publish a message to different subscribers with various kinds of subscribers including SMS, HTTP Endpoints or Webhooks, Amazon SQS, Lambda, Mobile Push etc. We will cover HTTP only subscribers in this post.

Kind of pub/sub where the publisher can publish a message and multiple interested subscribers can subscribe to that. You can read more on the AWS Website Here.

2. When you need AWS SNS?

When your project is distributed into various microservices and if you need to communicate from one or multiple microservices to other microservices then SNS comes to play a really good role.

Our Problem:

In our case, our project contains 3 different systems, where authentication + user management is handled by one central system. But each system has its local users table, where minimal users data is cached for fast data retrieval and table joins. so it doesn't need to query the central user system for each and every query.

If any new user is created by Admin on a central user management system, we need to notify other systems that a new user is created and they update their local users table.

3. How does it work?

Amazon SNS provides topics. You need to create a Topic and then define subscribers either programmatically or manually from Amazon Console. It depends on your use case. If you want to dynamically add subscribers then go that way or if you have some fixed microservices then you can define it from the console directly. This process works as follows:

  1. Create a Topic in AWS Console
  2. Create an HTTP subscriber
  3. SNS will send a SubscriptionConfirmation message to your HTTP Webhook
  4. Your microservice needs to call SubscribeURL
  5. Your subscription will be confirmed

This is the initial setup process. Once this is done. Everytime when any new message is published to Topic, it will call your webhook with that Message.

4. How to integrate it with PHP (Or any other PHP Frameworks like Laravel)?

Amazon has a very good PHP Library for their AWS products. Recently for SNS they have created another light-weight library to handle SNS Messages.

So we will use the following libraries in our integration.

Solution:

I will try to highlight the solution that we used to fix the above-mentioned problem. Check the following diagram:

As you can see, we set up an SNS Topic and created two HTTP/HTTPS subscribers for two different microservices. When an admin user creates a new user into the system, we publish a message to SNS Topic which sends an update to both different microservices.

Now, let's jump into the code.

Publishing a message:

You need to add aws/aws-sdk-php into your project. You can find installation steps on Github Repo. Also, you need to be familiar with AWS authentication process. These things are explained pretty well here. Collect all the things you need in terms of credentials.

  • Key
  • Secret
  • Region
  • Topic ARN

Following code hooked up into our central auth system. You can do this from wherever you want to publish your message. Create a client and then publish a message. You can pass two things into the SNS Message. Subject & Message body. Message body has several options. We will use a pure JSON string way for simplification.

use Aws\Credentials\Credentials; 
use Aws\Sns\SnsClient; 
$client = new SnsClient([     
      'version' => '2010-03-31',     
      'region' => $amazonRegion,    
      'credentials' => new Credentials(         
            $awsKey,         
            $awsSecret     
          ) 
      ]); 
      $subject = 'You got a new SNS Message'; 
      $message = json_encode([
      'message' => 'this is my first message via SNS Topic'
]); 
      $client->publish([    
      'TopicArn' => 'your-sns-topic-arn-here',     
      'Message' => $message,    
      'Subject' => $subject 
]); 

Generally, in our integration, what we did was, we used Subject to specify the type of event. Like Users.create, Users.update, Users.delete and Message used to contain user information. You can customize it based on your use-case.

That's it. Your message is published to a topic.

Handle Incoming SNS Message:

To handle SNS messages we need to integrate aws/aws-php-sns-message-validator into our project.

SNS will call our webhook for multiple kinds of events. It comes with Type param into the message body.

  • SubscriptionConfirmation
  • Message
  • UnsubscriptionConfirmation

Based on the Type parameter, we need to take relevant action. We have used the following code into our microservice webhook handlers.

use Aws\Sns\Message; 
use Aws\Sns\MessageValidator; 

try {     
// Retrieve the message     
$message = Message::fromRawPostData();   

// make validator instance     
$validator = new MessageValidator();   

// Validate the message     
if ($validator->isValid($message)) {         
      if ($message['Type'] == 'SubscriptionConfirmation') {  

// if it's subscription or unsubscribe event then call SubscribeURL             
      file_get_contents($message['SubscribeURL']);         
} elseif ($message['Type'] === 'Notification') {             
      $subject = $message['Subject'];             
      $messageData = json_decode($message['Message']);   

// use $subject and $messageData and take relevant action         
         }
     }
 } catch (Exception $e) {     // Handle exception .
} 

As you can see, based on Type, we are performing different operations.

This way, all our microservice can communicate in a very effective and highly available way to each other. Hope this helps :).

February 23, 20195 minutesauthorMitul Golakiya
post

Greetings friends. Finally, the InfyOm Labs blog is here.

This is my first blog, so, of course, this is my first post. so I spent quite a huge time reading how to start a blog. Let me take you in the past and give you a brief idea, how all these things were started.

Back in 2015, I just got started with full-time freelancing. It has been almost 2 years, I started working with Laravel. And recently Laravel 5 was just released in Feb 2015. It was a great time when the Laravel community was growing really fast. Lots of developers were accepting Laravel as their primary framework for their mainstream development.

In these 2 years, I worked on a lot of projects where I developed some CRM systems, Analytics Platforms, lots of APIs for mobile applications, etc. And the common problem that I found was, every time when I start a new module or a project, I have to create lots of common classes like, migration, model, controller, crud views files, repository, test cases, etc. And this was a problem for lots of developers.

Then I started to streamline this process and this is how my first laravel-api-generator package was born. In just a few days, it has been started to be used by lots of developers and I got a lot of feature requests.

mitulgolakiya/laravel-api-generator

Almost after a year, I realized that it was missing some modularity architecture where a community can have the option to customize it the way they want to use it. Like customizing CSS framework, generator templates, etc.

so I decided to rewrite a full package with a modular way and then the second version of the package was introduced with a new name InfyOmLabs/laravel-generator as a part of my new company's Labs project with a new website and detailed better documentation.

InfyOmLabs/laravel-generator

InfyOm Labs is a place where we do various experiments and release it as an open-source project for a community.

Again, we got a huge attraction and even this time in a short period of around 6-7 months we completed 1000 stars on our new InfyOmLabs Github Account.

Just after some time, I got comments from a community that there should be some blog where tutorials & videos should be posted to use the generator package for some newbie developers and some more complex features of the package.

Then today, I finally started a blog and will post tutorials and videos for Generator as well as for Laravel & PHP from time to time.

so stay tuned for the videos and tutorials. Also, I would like to hear your ideas about the tutorials and videos that you want to be posted here. Just post a comment about your ideas below.

Looking for the first idea to be submitted. :)

September 24, 20162 minutesauthorMitul Golakiya
post

Today we are going to take another major decision on our template development for Laravel Generator.

It's been around more than 7 months since we launched a new Laravel generator with the ability to select any CSS framework based on developers choice. Even anyone can develop his own templates and use it with a generator.

After these 7 months, now we have around 4 templates repository including Bootstrap Templates, AdminLTE Theme Templates, FlatLab Theme Templates, Metronic Theme Templates with maintaining templates for 3 different version of Laravel including 5.1, 5.2, 5.3. Also, laravel has a rapid release cycle, so it's very hard to maintain 4 packages with 3 different versions supported.

Also, what we realized is, lots of developers are using AdminLTE templates only for their main backend development. We found AdminLTE far better than any other templates. Also, It comes with a better setup, better elements support, regular updates and fits best for back-end Admin Panel development.

So today, we are taking a decision to actively only maintain AdminLTE templates and deprecate all other template development from our end. so we can focus on one template repository and can add more features to it.

It doesn't mean that packages will be deleted from its GitHub repository. It will always be there, but we will be focusing more on AdminLTE templates and all other templates will be more community driven.

September 27, 20161 minuteauthorMitul Golakiya
post

In this tutorial, we are going to learn how to display image in datatable or add image column to datatable while using yajra/laravel-datatables with infyom laravel generator.

We are continuously getting some questions like how we can achieve something with laravel generator. Recently, we got a question like, how we can display Image in DataTable while using yajra/laravel-datatables with infyom laravel generator. so I thought maybe it can be a requirement for lots of other developers as well and tried myself to find a solution. And then I decided to write a tutorial on that, so other developers can get an idea on that.

so here is the use case, suppose we have a Post model which contains three fields,

  1. Title
  2. Image
  3. Body

Image field contains a full or relative URL of the image which we need to show in a datatable (same as above image).

When you are using InfyOm Laravel Generator it generates PostDataTable.php file for the definition of DataTable. That file contains a function named, getColumns() for the definition of columns of DataTable. Something like following,

 return [     
   'title' => ['name' => 'title', 'data' => 'title'],     
   'image' => ['name' => 'image', 'data' => 'image'],     
   'body'  => ['name' => 'body', 'data' => 'body'] 
]; 

This is a very simple implementation of a DataTable Column definition.

To Display images in DataTable, we need to use the `render` function on the column to display images. You can define your own render function which will return the data that should be rendered in the column. In our case, we want to render an image, so our render function will be something like following,

 return [     
   'title' => ['name' => 'title', 'data' => 'title'],     
   'image' => ['name' => 'image', 'data' => 'image'],     
   'body'  => ['name' => 'body', 'data' => 'body'] 
]; 

If you will look carefully, we are returning, from render function. Where data will be the data from the model. In our case, It will be a URL.
Render function gets the data parameter as a first argument. You can find more information about render function over here.

Above code will generate output something like following,

"name": "image",    
   "data": "image",    
   "render": function (data, type, full, meta) {        
        return <img src=\"" + data + "\" height=\"50\"/>;     
},     
   "title": "Image",    
   "orderable": true,   
   "searchable": true 
}

So, this is how we can display an image in a datatable.

September 30, 20162 minutesauthorMitul Golakiya