Tips Posts

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 minutesauthorMitul Golakiya
post

What is a PWA?

A Progressive Web App (PWA) is a hybrid of a regular web page and a mobile application. A PWA combines features offered by most modern browsers with the benefits of the mobile experience. They are built using standard web technologies, including HTML, CSS, and JavaScript. The functionalities include working offline, push notifications, and device hardware access and enabling creating user experiences similar to native applications.

How to make a PWA

Following Below steps

  • Create an app manifest.json file
  • Add it to your base HTML template
  • Create the service worker
  • Serve the service worker on the root of the scope you used in the manifest
  • Add a block to your base HTML template file
  • Site deploy in your server

Create an App Manifest

  • Add the following information in 'manifest.json'
 {
    name: `Name`,
    short_name: `Sort name`,
    start_url: `/`,
    display: `standalone`,
    icon:  `Favicon icon`,
    icons: [
       {
        "src": "icon by size",
        "sizes": "144x144",
        "type": "image/png",
        "purpose": "any"
      },
      {
        "src": "icon by size",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
      },
      {
        "src": "icon by size",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
      }
    ],
  theme_color: `Theme color`,
  background_color: `Background color`,
  ]
 }
  • Manifest.json file in add this type of code including name, short_name, start_url, display, icon, icons, theme_color, background_color.

Add the Manifest to Your Base HTML Template

  • Add the following line in yore 'index' file

Create offline.html as an Alias to index.html

By default, the service worker code below will render /offline.html instead of any resource it can't fetch while offline. Create a file at /offline.html to give your user a more helpful error message, explaining that this data isn't cached and the user is offline.

Create a Service Worker

  • Create one file in yore root (sw.js)
  • Link the sw.js file in the body tag

We have created some pages like

  1. Home page (/)
  2. Blog page (/blog)
  3. Contact information (/contact)
  4. Resume (/resume)
  5. offline.html
  • Add the code in your sw.js file
self.addEventListener("install", function(event) {
   event.waitUntil(preLoad());
});

 var preLoad = function(){
  return caches.open("offline").then(function(cache) {
    return cache.addAll(["/blog/", "/blog", "/", "/contact", 
 "/resume", "/offline.html"]);
    });
 };

 self.addEventListener("fetch", function(event) { event.respondWith(checkResponse(event.request).catch(function() 
  {
     return returnFromCache(event.request);
   }));
   event.waitUntil(addToCache(event.request));
  });

  var checkResponse = function(request){
   return new Promise(function(fulfill, reject) {
     fetch(request).then(function(response){
       if(response.status !== 404) {
         fulfill(response);
       } else {
         reject();
       }
     }, reject);
   });
  };

  var addToCache = function(request){
   return caches.open("offline").then(function (cache) {
     return fetch(request).then(function (response) {
       console.log(response.url + " was cached");
       return cache.put(request, response);
     });
   });
  };

  var returnFromCache = function(request){
   return caches.open("offline").then(function (cache) {
     return cache.match(request).then(function (matching) {
      if(!matching || matching.status == 404) {
        return cache.match("offline.html");
      } else {
        return matching;
      }
     });
   });
  };
  • Servicer worker file add your body tag

load the service worker file in

 

Last step

  • Deploy code in yore live site
  • Create lighthouse report and check PWA
July 28, 20214 minutesauthorVatsal Sakariya
post

Email marketing is an effective way to increase your sales. Email marketing is an easy way to sell your product without any charge with a high ROI.

People said the email marketing technique is not useful to sales. but it’s not real today in 2021 almost all people use email. So we can easily reach out to them and increase sales using email marketing.

First, know the term What is email marketing?

  • Email marketing is an effective digital marketing strategy to sending emails to customers related to product sales and increase sales using email marketing.

The importance of email marketing for increase sales

Email marketing is the two-way communication channel

  • Email marketing is the two-way communication channel where people send a reply back to your mail easily so communication is faster and you can easily sell your product and increase sales using email marketing

Your own email list

  • In some social media, sometimes your account is banned with large community fans but email marketing is the only way to create your own email list so no one can ban you or nobody can your leads away from you.

Email use for better conversion

  • Email marketing has a huge ROI(Return of Investment) of 4400%. No one social media has a huge ROI like email marketing. Do you think to increase your sales using email marketing?
  • Every people wants to increase sales using email marketing with high profit.

4 Ways to do email marketing and increase your sales

Built an email list

  • Built an email list of subscribers who interesting in what you offering. The best way to create an email marketing list is to create a personal audience and send mail to them.

  • First, think email list all person is your customer and some of them from different niche. They don’t like to receive from unrelated or different topics for a niche.

  • So, Built an email list who have interested in your product.

Maximize your email list

  • You know more people coming out to your website, offer the customer free templates, checklists, eBooks, etc.

  • The most ideal approach to create drives that are really inspired by your item is by offering a lead magnet that tackles an issue for customers. For the most part, lead magnets are digital books, agendas, or exhaustive aides that your crowd can use to determine a problem area identified with your business.

Segment your lead list

  • Do not directly sell your product because nobody can purchase a product for you.

  • First, know the customer interest and send 4 to 5 emails or offer some on your product.

  • After customers convince about your product then sell your product.

Ensure email is delivered or not

  • After sending an email know email is delivered or not.

  • Is the best way to increase sales using email marketing
July 27, 20212 minutesauthorAnkit Kalathiya
post

Lots of developers have a question How do I set up React in the Laravel application? so, In this article, I show you how to set up a React in Laravel.

We have a video tutorial as well. so, you can watch it or follow this article.

Follow the following steps

I hope you created a Laravel application in your local machine.

You should watch this tutorial first if not and don't know how to create a Laravel application.

Steps 1:

Let's navigate to the resource directory of your laravel application.

Now, create react application using npx create-react-app react-app. also, you can follow an official docs.

Steps 2:

Now, move all the packages from the package,json to package.json which is located in the root directory of the laravel application.

Steps 3:

Run the following command,

npm install

Steps 4:

We need to compile the react application and convert it into js file. so, let's use laravel mix.

Let's open a file webpack.mix.js and put the following code,

 mix.options({
  postCss: [
      require('autoprefixer'),
  ],
});

mix.setPublicPath('public');

mix.webpackConfig({
  resolve: {
      extensions: ['.js', '.vue'],
      alias: {
          '@': __dirname + 'resources'
      }
  },
  output: {
      chunkFilename: 'js/chunks/[name].js',
  },
}).react();

// used to run app using reactjs
mix.js('resources/react-app/src/index.js', 'public/js/app.js').version();
mix.copy('resources/react-app/public', 'public');

Steps 5:

Fire the following command for compile the assets,

npm run dev

Steps 6:

React application compiled successfully and created all files in the public directory. now, we need to include this js file into the laravel root file. I guess we have a fresh laravel project. so, let's add in welcome.balde.php. you can add in any file where you want to load react application.

Include the following line before end the body,

<script type="text/javascript" src="{{ mix('js/app.js') }}"></script>

also, one more thing we should not forget to include a <div id="root"></div> in root file of laravel. I going to put right now into welcome.blade.php

The last step is just to fire the artisan command php artisan serve and open this URL http://127.0.0.1:8000 in the browser.

July 24, 20212 minutesauthorShailesh Ladumor
post

Today we are going to see how we can image based on resolution. We have the most common issue of loading big images in small devices take time. So, the basic solution is to use the picture element to load a different image in different devices and resolutions.

The <picture> element will be for the art direction of responsive design.

The element contains two tags.

  • <source>
  • <img>

So, the browser will look for the first <source> element where the media query matches the current width, and then it will display the image. The <picture> element is required as the last child of the <picture> element.

Let me show you an example of how to display a different image in different widths.

Here is a Code example,

<picture>
    <source media="(min-width:900px)" srcset="infyom_logo_lg.jpg">
    <source media="(min-width:700px)" srcset="infyom_logo_md.jpg">
    <source media="(min-width:500px)" srcset="infyom_logo_sm.jpg">
    <img src="infyom_logo_xl.jpg" alt="Flowers" style="width:auto;">
</picture>
June 18, 20211 minuteauthorShailesh Ladumor
post

Recently,  I've started working on one project where we need to set up a virtual host with HTTPS because I need to run that project with expose and Shopify in my local development machine. I've wamp 3.2.3 on my local machine.

I spend a lot of time for setup it. so, I thought I should write one article for step by step guide. So, I show you in this article how to setup HTTPS for a local machine.

Step 1 - Install Wamp

Install wamp server if not installed in your local machine. you can download the latest version of the wampserver from here. wampserver is available in 32 bit and 64 bit. make sure you select the correct version of the wampserver based on your operating system (window)'s version.

Step 2 - Install OpenSSL

OpenSSL is an open-source command-line tool that is used to generate the SSL certificate and private key. OpenSSL is available in both versions 32 and 64 bit. download the latest version of OpenSSL from here.


I hope you successfully installed OpenSSL on your machine. let's take the next step

Step 3 - Create a Private key

Open your terminal as an Administrator otherwise you will get a permission denied error. also, you can provide permission to the OpenSSL directory and run the terminal on normal mode.

Now, let go to where we installed OpenSSL

cd C:\Program Files\OpenSSL-Win64\bin

Let's create a private key which is 2048 bits encryption.  fire one by one the following two commands to create it.

openssl genrsa -aes256 -out private.key 2048
openssl rsa -in private.key -out private.key


Your private.key is successfully generated here C:\Program Files\OpenSSL-Win64\bin 

Step 4 - Create an SSL Certificate

Let's create a certificate using the following command,

openssl req -new -x509 -nodes -sha1 -key private.key -out certificate.crt -days 36500

You need to enter a detail looks like


You can verify here 

Step 5 - Move both Private Key and a Certificate

Open a directory D:\wamp64\bin\apache\apache2.4.46\conf (Based on where your wamp is installed) and create a `key` directory.

Now, move both files to the `key` directory.

Step 6 - Configure Your httpd.conf File

Open your `D:\wamp64\bin\apache\apache2.4.46\conf\httpd.conf` (the drive should be where your wamp is installed) and un-comment the following 3 lines one by one.

LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so

Step 7 Configure Your httpd-ssl.conf File

Open your `D:\wamp64\bin\apache\apache2.4.46\conf\extra\httpd-ssl.conf` (the drive should be where your wamp is installed) and change the all following lines.

DocumentRoot "${INSTALL_DIR}/www"
ServerName localhost:443
ServerAdmin admin@example.com
SSLCertificateKeyFile "${SRVROOT}/conf/key/private.key"
SSLCertificateFile "${SRVROOT}/conf/key/certificate.crt"

Make sure, these following all lines are set or not. if not, add it as well.

SSLSessionCache "shmcb:${SRVROOT}/logs/ssl_scache(512000)"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

Step 8 Configure a Virtual Host

Hope you have created a virtual host. if not, create a virtual host using virtual host manager which is provided by wamp.

Open an `D:\wamp64\bin\apache\apache2.4.46\conf\extra\httpd-vhosts.conf` and update your virtual host

Change the  port *:80 to *:443

add following lines into the VirtualHost.

SSLEngine on
SSLCertificateFile "${SRVROOT}/conf/key/certificate.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/key/private.key"

Now, the code of VirtualHost looks like, 

Now, we are done. Let's restart a wamp server.

If you see a green WAMP icon everything should be right. If the icon is orange there is a problem with your syntax somewhere. 

Open terminal and go to the `D:\wamp64\bin\apache\apache2.4.46\bin` and run `httpd -t` in the command prompt and if there are any syntax errors they will be listed.

if fine then open `https://ladumor.test` on the browser

January 30, 20213 minutesauthorShailesh Ladumor
post
While developing complex applications, sometimes we have to validate fields and data in a totally customized way, at that time you can use laravel's custom validations rules functionality. 

In this tutorial, we are going to create our own custom validation rule to compare UUID. In our case, I have to check the UUID which is actually a binary string, that exists on DB or not.
Laravel doesn't provide any rule to compare that binary UUID string, so we will create our own validation rule. 

So let's create our custom validation rule::

Generate Custom Validation Class

So here we have created new class with named UuidExists into App\Rules

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Ramsey\Uuid\Uuid;
class UuidExists implements Rule
{
   
    protected $table;
    protected $column;

    public function __construct($table, $column)
    {
        $this->table = $table;
        $this->column = $column;
    }
    public function passes($attribute, $value)
    {
        $value = Uuid::fromString(strtolower($value))->getBytes();
        return \DB::table($this->table)->where($this->column, $value)->exists();
    }
    public function message()
    {
        return 'The validation error message.';
    }
}


Add Rule to AppService Provider

Add your rule to AppServiceProvider.php into boot() method. here I have to give the named uuid_exists to my custom rule. you can give your own name whatever you want. 

\Validator::extend('uuid_exists', function ($attribute, $value, $parameters, $validator) {
  list($table, $column) = $parameters;
  return (new UuidExists($table, $column))->passes($attribute, $value);
});

How to use custom Rule ?

You can use your custom rule as follows. here we have using required and uuid_exists rule, where we are passing attribute and values to our custom rule, which will be used to passes($attribute, $value) function.

'tenant_id' => ['required', 'uuid_exists:tenant_id,uuid']

Keep connected to us for more interesting posts about Laravel.


January 21, 20211 minuteauthorVishal Ribdiya
post

GIF logo file formats are not as widely used as they once were. They have a very limited color spectrum (only 256 colors out of millions in JPG) so solid color logos are a good candidate for this format. A special feature of the GIF file is that it supports smooth animation. You can create frames with frame animations and file sizes will be negligible as long as you keep the color flat and smooth (from red to blue). GIF files are pixel-based and do not expand well.


EPS and AI logo file formats are a sacred grail of file formats. They are made up of dots and lines, not pixels, allowing infinite scaling and expansion without losing quality. Many business owners and executives ignore these logo file formats because they cannot open them normally. Many common MS Office fee programs do not open the EPS logo file format. EPS files can also support pixels, which also makes this file format difficult. Software such as Adobe Illustrator, InDesign, or Photoshop can work with this file format and optimize and save almost any logo file format you need. Illustrator will allow resizing, color mode change, and more.

PDF logo file formats can also be difficult as PDF color mode can disguise spectra and resolution. Some common office fee software will open or import PDFs but one way to tell if the resolution is good is to zoom in very closely to the logo. If the edges stay crisp, you’re in business and a graphic designer who can use something in print and digital applications. If the edges become blurred or pixelated, you will be limited in the use and extension of this particular logo file format.

SVG files have become more common on websites and digital access and are considered the standard format for displaying vector graphics on the web. SVG logo file formats allow a resizable logo format that does not lose image quality as it is expanded or reduced. This is especially important with responsive web design where the logo file can be resized depending on the digital device the website is viewing. Another major advantage for the SVG logo file format is the relatively small file size - which allows a digital file to load on a website very quickly. Support is limited to SVG but website design is an important place for their use.

January 08, 20212 minutesauthorKishan Savaliya