InfyOm Blog

latest-post

Last week, we run into a problem for one of the large Gatsby + ReactJS + Laravel projects in hosting which is hosted with Apache Webserver on Amazon AWS EC2. The problem we were facing was, for some reason, when we reload the Gatsby website, it was giving a 404 error page.

If you open a home page and then a normal visit then the website will fully function, but if you reload the page then it gives an error. And we found it happens when we are using Dynamic routing of React Route in Gatsby as per show in Gatsby documentation here.

Also, what we found, if we test the website build with gatsby serve then it works fine. But while using Apache, it behaves differently and we found that this problem has been faced by lots of people over the internet.

So what we came up with is, we used gatsby serve with an apache proxy. Here is how we did it,

Step 1 - Setup Project

As a first step, clone the project on the server and run a command, gatsby build to create a gatsby build.

Step 2 - Setup PM2 for Gatsby Serve

The next step that we need to do is run gatsby serve. But as you know, we can not run this command directly via console, because as you exit from the console, the command will be terminated.

So we will be using pm2 package, a NodeJS utility that is used to run nodejs apps.

For that, we will need to install pm2 globally. Run the following command to install it,

npm install pm2 -g

You can find other installation ways here if you need.

Once the installation has been done, let's run the gatsby serve command via pm2. For that run the following command from the gatsby project folder,

pm2 start gatsby --name my-web-app -- serve

where my-web-app you can replace with the name of your app.

Once, it's running, try to test it, if it's working correctly by opening the URL http://your-ip-address:9000/. Make sure, port 9000 is opened on your server for traffic.

Step 3 - Configure Apache

Once, gatsby serve is working and tested. The next step is to configure apache to proxy all port 80 traffic to port 9000.

For that, edit your apache conf file (or virtual host conf file), and add the following lines (or configure it to something like the following),

<VirtualHost *:80>
        ServerName my-web-app.infyom.com

        ServerAdmin webmaster@infyom.com

        ProxyRequests On
        ProxyPass / http://localhost:9000/
        ProxyPassReverse / http://localhost:9000/

        ErrorLog ${APACHE_LOG_DIR}/my-web-app.infyom.com.error.log
        CustomLog ${APACHE_LOG_DIR}/my-web-app.log combined

        ......
        # any other options below as per your need
        ......
</VirtualHost>

The next step you need to do is restart your apache server by,

sudo service apache2 restart

And then you can just open the URL https://my-web-app.infyom.com and it should work fine.

Bonus

New Deployment

Whenever you deploy a new code, you again need to run gatsby build and then pm2 restart my-web-app. Then only it will take new changes.

Troubleshooting

Sometimes, we found that we need to restart apache as well after the new deployment. so if you run into any trouble, then make sure to restart apache as well and it should solve the problem.

I hope it may help you to resolve your 404 problem.

July 16, 20213 minutesuserMitul Golakiya

Posts

post

In Last Podcast and Blog Post, we discussed how we need to create 4 departments in our business and become A-Karta in our organization.

But just becoming A-Karta doesn't work. So in verse 7 & 8, Lord Shree Krishna said and this is one of the most popular verses of Bhagavad Gita,

यदा यदा हि धर्मस्य ग्लानिर्भवति भारत |

अभ्युत्थानमधर्मस्य तदात्मानं सृजाम्यहम् || 7 ||

परित्राणाय साधूनां विनाशाय च दुष्कृताम् |

धर्मसंस्थापनार्थाय सम्भवामि युगे युगे || 8 ||

હે ભારત! જયારે જયારે ધર્મ ને હાનિ થાય છે અને અધર્મનું જોર વધે છે, ત્યારે ત્યારે હું જન્મ ધારણ કરું છું. સત્પુરુષોનાં રક્ષણ માટે, દુષ્ટોના વિનાશ માટે અને ધર્મની સારી રીતે સ્થાપના કરવા માટે હું યુગે યુગે પ્રકટું છું.

Whenever there is an increase in unrighteousness, Lord appears on earth age by age, to protect the righteous, to annihilate the wicked, and to re-establish the principles of dharma.

Same way when our 4 created departments do not do their work or perform their duties or do not produce desired results, then we also need to come in the picture time by time.

Whenever there is an increase in unrighteousness - People do not perform their duties or you do not get results

Lord appears on earth age by age - You need to come in the picture time by time

protect the righteous, to annihilate the wicked - to protect your culture & company & its people

and to re-establish the principles of dharma - to re-establish the balance and processes of the company.

You can also listen to the full podcast here.

February 01, 20201 minuteauthorMitul Golakiya
post

4 Varnas in Hinduism

Image Source

Shreemad Bhagavad Gita has a lot to speak about business management. In the last Post of Karma-Yoga, we have seen how our actions should be for the benefits of the others. Today, let's see Chapter 4.

In Chapter 4, Karma-Brahm-Arpan-Yoga (Jñāna Karm Sanyās Yog), verse 13th and 14th, Lord Krishna said,

चातुर्वर्ण्यं मया सृष्टं गुणकर्मविभागश: |

तस्य कर्तारमपि मां विद्ध्यकर्तारमव्ययम् || 13 ||

The four categories of occupations were created by me according to people’s qualities and activities. Although I am the creator of this system, know me to be the non-doer and eternal. (source: holy-bhagavad-gita.org)

પ્રકૃતિના ત્રણ ગુણો એન્ડ કર્મોના વિભાગ પ્રમાણે મેં બ્રાહ્મણ, ક્ષત્રિય, વૈશ્ય અને શુદ્ર એમ ચાર વર્ણોની રચના કરી છે. તેનો હું કર્તા હોવા છતાં પણ તું મને અકર્તા અને અવિકારી જાણ.

न मां कर्माणि लिम्पन्ति न मे कर्मफले स्पृहा |

इति मां योऽभिजानाति कर्मभिर्न स बध्यते || 14 ||

Activities do not taint me, nor do I desire the fruits of action. One who knows me in this way is never bound by the karmic reactions of work.(source: holy-bhagavad-gita.org)

કોઈ કર્મો મને લેપતા નથી, કેમ કે કર્મોના ફળમાં મને લાલસા નથી. આ રીતે જે મનુષ્ય મને જાણે છે, તે પોતાના કર્મો વડે બંધાતો નથી.

Based on occupation & activities, God created the following 4 Varnas:

  • Brahmins - predisposed toward teaching and worship (how to get the God or go to heaven)
  • Kshatriyas - inclined toward administration and management of the kingdom
  • Vaishyas - form the business and agricultural class (Businessmen)
  • Shudras - working class (The actual person who works)

In the same way, we also need 4 Departments in our Business.

  • Brahmins - Marketing - Do the marketing & they actually help us to meet our God (Our Customer).
  • Kshtriya - HR - Form a Business, Hire Team, Appoint People, Make Policies, define Penalties, etc.
  • Vaishyas - Operations - Administration & Management (or your Top Management Team).
  • Shudra - Technical - Actual working people, our employees who actually do work

What God did is, created these 4 Varnas and given them their duties and activities that they need to perform and he simply became A-Karta (non-doer and eternal).

We as CEO, also need to do that same thing. Create these 4 Departments, assign them their duties and just become an external observer. Then all you need to do is, whenever they got stuck, help them, guide them or train them. That's it.

So just simply, Be a God of your Company.

You can also listen to full podcast here.

January 24, 20202 minutesauthorMitul Golakiya
post

2019 was a great year for us in terms of business as well as in my personal life. We have some major breakdowns which taught us lots of good lessons while we resolved it.

1. Do not get your company to rely on one major client

The major mistake we made was our 80% staff was working for one client for years. And when that work got stopped the 80% company has no work with 50% staff was a senior and experienced developer with top salaries.

Of course, long term relationship is important but always keep working with multiple clients/people. It will keep your business moving even if one of your work got stopped for whatsoever reason. Because even if you have top talent, getting really good clients is too tough in the market.

2. Everything starts with YOU

Before you transform your business, the first thing that needs to be transformed is yourself. Once you start transforming, everything else into your business, your team will start transforming automatically.

Your team learns a lot from you, they are your main observers. Once they see you transforming, their life will also start getting transformed.

3. Wake up Early

All great leaders are early birds. Once you win your morning, you can win the rest of the day. 3 hours of early mornings are the main productive hours. That’s the time when you can complete your things which you are not able to complete throughout your day or you are not getting time for.

Also waking up at fixed early morning time will help you a lot in your health. Wake up at 5 am at least, do some exercise, reading and complete the most important thing of the day in the morning only.

4. Power of Reading

“Not every Reader is a Leader but every Leader is a Reader.”. This sentence has a lot to say. Once you start reading it will transform your life a lot. The good book contains years of research by the author. So you can directly get those years of knowledge by reading that book in just a few days.

5. Increase your Networking

I will say you should meet lots of people. Meet them, talk with them, know them, learn from them even if you are not working with local people.

Plan to meet one good CEO or Coach every month. Invite them to lunch or dinner and try to learn as much as you can from them. Ask about their processes, structures, systems, technologies, etc.

6. Contribution in other’s lives

When you contribute to other people’s lives, that contribution will come directly back to you by double. When you transform their life, your life will automatically get transformed.

7. Get a Coach or Mentor

Always surround yourself with Coaches and Mentors at every and each stage of life. In Business and Personal life as well. Your coach can be anyone from Friends, Family or some specialized Mentors and Coaches.

You always need someone who can push you, help you, guide you. Get someone who can give your honest and transparent advice and guidance.

8. Never stop Learning

Never stop learning. Always learn something every day or at least a week. Read Books or Watch Videos or Learn new technologies or Purchase some Courses. Even if you are super busy, put a dedicated time to watch 10 mins video or Read 10 mins every day.

In the long run, just 10 mins of every day will help you a lot.

9. Write Daily Journal

Writing your daily Journal helps a lot. List down your today’s achievements and your tomorrow’s goals. It will help you to track your daily progress as well as plan your day of tomorrow.

When you write a Journal, you will have an exact idea on the next day, what are your priorities in the morning only. Once you plan your day ahead a day, it has tremendous benefits.

10. Delegation

Delegation is really powerful. Before doing any task, just think if you can delegate it then delegate it. Your time is limited and precious, put it on the things where it’s actually needed rather than doing things that someone else can do from your team.

And if they are not able to do it right now, start training them and make them capable to take off your load.

11. Power of ToDo List

Start Maintaining To-Do list. It has huge power and will bring a great impact. Anything that you need to do, add to your ToDo list. Need to make a call to a friend? add it. Need to send an Email to the client? Add it.

Each and every small thing should be added to the ToDo list with a due date if possible. It will help you to prioritize your tasks and will give you motivation at the end of the day when you check the list of complete things.

12.Write a Blog

Start writing your blog. It doesn’t need to be fancy or content-rich. Just write down anything that seems to be useful to at least one person in the world. Just write down about things that came to you across the day.

Your blog post doesn’t need to long. Just write 2-3 small paragraphs and that’s it. But at least start writing something daily/weekly whatever is possible for you.

Hope you enjoyed it and see you next year with new learnings.

January 23, 20204 minutesauthorMitul Golakiya
post

In the second chapter of Gita Lord Krishna said,


कर्मण्येवाधिकारस्ते मा फलेषु कदाचन |

मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि ||

that means, "You have a right to perform your prescribed duties, but you are not entitled to the fruits of your actions."


And this is where most of the people got confused. If I do not have any expectations then how I will get motivated to do something.

For e.g., As a product owner, If I do not expect that my product should grow to whatever level, why I would put my efforts into that.

So Arjuna asks the same question to Lord Krishna, "If I should not keep any expectation about my kingdom then why do you urge me to jump into this war?"


What Karma-Yoga says is, Everyone must engage in some sort of activity in this material world. In short, do actions. You can not run away from your duties or actions. But those actions should be selfless actions that are performed for the benefits of others.

Because in chapter 3, verse 13, Lord Krishna said,

यज्ञशिष्टाशिन: सन्तो मुच्यन्ते सर्वकिल्बिषै: |

भुञ्जते ते त्वघं पापा ये पचन्त्यात्मकारणात् || 13 ||

that means, The spiritually-minded, who eat food that is first offered in sacrifice, are released from all kinds of sin. Others, who cook food for their own enjoyment, verily eat only sin. (source: holy-bhagavad-gita.org)


In our business, every day we should be generous and gracious to the people we work with. Also, we should build a socially responsible business, which means being aware of the company’s impact on workers, consumers, and the environment around it. That means happier employees, who builds better products and ultimately happy customers.


A business can make lots of money, be successful, and grow for years but it should be still giving back to society, providing services, and improving the community around it.

January 18, 20201 minuteauthorMitul Golakiya
post

Last month, I got consulting of one Laravel project where we have to perform some complex validations.

The scenario was while creating an order, either customer can select the existing address from the dropdown or he may have an option to create a new address with all address fields.

And when a customer hits enter, the backend needs to validate, if address_id is sent into request then it needs to check if that address id exists and then use that address_id for that particular order. Otherwise, it needs to check if required fields (address1, city, zip, country) for address are sent then use them, create a new address and use that new address_id.

so far how validation was happening was manual, so in controller this all manual validation was happening. But I don't find that a proper way. The goal was to do validation from CreateOrderRequest only. so it goes back with proper laravel error messages from a request only and displays them on the page. so we actually do not need to make any manual efforts to make this happen.

That's where required_without validation rule helped us.

The UI was something like this,

required-without-laravel-validation-rule.png

In the above UI, customers can either type Address1, Address2, City and Zip or just go and select an existing address from the dropdown.

To do this validation from form request, we used the required_without rule as following, 'address_id' => 'required_without:address_1,city,zip|sometimes|nullable|exists:addresses,id',

Now let's try to understand what's happening here. To understand it better let's divide the rules

  1. required_without:address_1,city,zip
  2. sometimes
  3. nullable
  4. exist:addresses,id

1. required_without:address _1,city,zip

This rule validates that address_id field is required without the presence of address_1, city and zip fields

2. sometimes

This means, address_id fields will be passed only sometimes and not required all the time. We need this because when address_1, city and zip fields will be present then we do not need it at all.

3. nullable

This means, address_id fields can be null since it will be null when a customer does not select the address from the dropdown.

4. exist:addresses,id

The passed value in address_id fields, must exist in the addresses table.

So this is how we solved this complex validation in a very easy way by using multiple powerful laravel validation rules.

Hope this can help others as well.

January 07, 20202 minutesauthorMitul Golakiya
post

Last week, we were working on one project where we were using LaravelCollective for generating our form. LaravelCollective is a really awesome package and reduces lots of efforts, specifically for automatically binding old inputs to our forms.

Problem

With LaravelColletive when we pass null as a second value, it tried to get old inputs if available and inject them. But for some reason, it was not working with datetimelocal.

datetimelocal need a date in Y-m-d\TH:i Format. When I went into the code of FormBuilder.php, it’s already managing that and tries to convert date into that format if you have passed DateTime object.

So it was completely working fine while creating a record when you do not have any value.

But I have the same form which was used at both the time of Create and Update. And I was passing null into value field at both of the time and LaravelCollective injects it automatically from model or old inputs if there is some error. Something like following,

<div class="form-group col-sm-6">
    {!! Form::label('due_date', 'Due Date:') !!}
    {!! Form::datetimeLocal('due_date', null, ['class' => 'form-control']) !!}
</div>

So, Due date will be automatically placed from the model. It’s working fine with all other fields except datetimelocal.

Solution

The reason behind that is, the value is retrieved from model due_date field, but it comes in Carbon instance and when it converts to a date string, it’s converted into default format which is Y-m-d h:i:s. So it will not work for datetimelocal input since it requires Y-m-d\TH:i format.

So as a solution, what change we did is, instead of passing null value, we first check, if the model is there then pass the value directly to the input. Something like,

<div class="form-group col-sm-6">
    {!! Form::label('due_date', 'Due Date:') !!}
    {!! Form::datetimeLocal('due_date', (isset($task)) ? $task->due_date : null, ['class' => 'form-control']) !!}
</div>

So, I will check if I have passed the model $task to the view and then I will pass a due_date value to input. So FormBuilder will convert it to the proper format and it will get displayed into an input.

Now, when we save the form, it will also return date into Y-m-d\TH:i format, so again we need to convert it to the proper format. For that, we created a mutate attribute for due_date in my Task Model.

public function setDueDateAttribute($value)
{
   $this->attributes['due_date'] = Carbon::parse($value);
}

And that’s it. Our datetimelocal input gets working. I have seen lots of issues on stackoverflow for it. So hope it may help someone.

November 14, 20192 minutesauthorMitul Golakiya
post

In the previous article, we learned How to create Laravel Facade and how it can help to simplify our code and make it more accessible and beautiful.

In this article, we will see how we can control our SMS Provider/Gateway via configuration without even touching the code and change it from the environment directly.

Use Case

Imagine you have two SMS Providers called ABC and XYZ that you are using into our application. But you need to switch it over time. But the trick is, you do not want to change your code when you change to other SMS service provider. Just like when you change any driver in Laravel App like Log, Cache, Queue, Database, etc.

so let's figure out, how to do that.

Solution

Create SMS Service Contract

Create an SMS Service contract interface that contains the method to send the SMS.

Create a class app/Services/Contracts/SMSServiceContract.php with the following content,

<?php

namespace App\Services\Contracts;

interface SMSServiceContract
{
    public function sendSMS($phone, $message);
}

The purpose of this class is, every SMS Service should implement this interface and it should have at least one method sendSMS with given the same parameters.

Create SMS Service Implementations

The second step is to create the real implementation of our SMS Services which will be responsible to send the SMS.

So as we have two SMS services, we will create two classes,

ABC SMS Service

Create a class app/Services/ABCSMSService.php with the following content,

<?php

namespace App\Services;

class ABCSMSService implements SMSServiceContract
{
    public function sendSMS($phone, $message)
    {
        // Code here to call API of ABC SMS Provider to send SMS
    }
}

XYZ SMS Service

Create a class app/Services/XYZSMSService.php with the following content,

<?php

namespace App\Services;

class XYZSMSService implements SMSServiceContract
{
    public function sendSMS($phone, $message)
    {
        // Code here to call API of XYZ SMS Provider to send SMS
    }
}

Create Facade to Send SMS

The third step is to create a Facade to send an SMS. Create a facade class app/Facades/SMSGateway.php with the following content,

<?php

namespace App\Facades;

use App\Services\Contracts\SMSServiceContract;
use Illuminate\Support\Facades\Facade;

class SMSGateway extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return SMSServiceContract::class;
    }
}

Here, note that we are giving SMSServiceContract class name as a facade accessor. So we will need to use that same class name while binding it to the real implementation in our service provider.

Define SMS Driver in config

We need to define our SMS Driver into our config file. You can create a new config file or can use config/services.php. To keep it simple, we will define it in services.php. I will add the following content at the end of the file before the closing bracket. so it will look like something,

<?php

return [
    ...
    'sms' => env('SMS_SERVICE')
]

Define your driver in .env file

Update your .env file and add SMS_SERVICE variable, something like

SMS_SERVICE=abc

Create/Modify Service Provider

The final step here is, we need to either create our own service provider and add it to config/app.php or we can use AppServiceProvider.php as well. To keep it simple let's add it to AppServiceProvider.

In app/Providers/AppServiceProvider.php we will add the following code under the register method,

$this->app->bind(SMSServiceContract::class, function ($app) {
    if (config('services.sms') == 'abc') {
        return new ABCSMSService();
    } else {
        return new XYZSMSService();
    }
});

Note: Do not forget to import all these classes at the top.

And that's it.

Usage

Now you can use your Facade to send the SMS.

\App\Facades\SMSGateway::sendSMS($phoneNumber, $message);

Or if you made an alias,

\SMSGateway::sendSMS($phoneNumber, $message);

Change service provider,

Now if you want to change your service provider, all you need to do is, just go to the .env and change the provider to xyz and it will use the XYZSMSService class to send the SMS.

I hope this will help to understand Laravel Service Providers and Facade in a much better way.

November 08, 20193 minutesauthorMitul Golakiya
post

We are working on an inventory system for one of our client for a long time and recently, what we needed was to retrieve inventory item information by UPC code or ISBN or EAN. so the end customer does not need to fill a full form with all the details.

We implemented a feature where customers can just enter or scan UPC/ISBN/EAN code on the mobile app and we retrieve all the information of the product and auto-fill it with an image of the product as well.

So we started using UPCItemDB, which has a very nice database of items. You can call their API and retrieve information about the product by sending UPC code. It has a free plan that you can use for trial purposes.

But there was no proper PHP or Laravel package for that, so we decided to make our own and publish it to Github.

It's called laravel-upcitemdb and here is the link for it: https://github.com/InfyOmLabs/laravel-upcitemdb

Here are the installation steps and how to use this package.

Installation

Install the package by the following command,

composer require infyomlabs/laravel-upcitemdb

Publish the config file

Run the following command to publish config file,

php artisan vendor:publish --provider="InfyOm\UPCItemDB\UPCItemDBServiceProvider"

Add Facade

Add the Facade to your config/app.php into aliases section,

'UPCItemDB' => \InfyOm\UPCItemDB\UPCItemDB::class,

Usage

Lookup

For UPC Lookup, use the lookup method by calling,

\UPCItemDB::lookup('4002293401102');

Search

For Search API, you can use the search method,

\UPCItemDB::search('iphone 6');

\UPCItemDB::search('iphone 6', [
    'brand' => 'apple'
]);
November 05, 20191 minuteauthorMitul Golakiya