author-img

Shailesh Ladumor's Posts

Web Development Head

post

We have recently developed a site into the gatsby.

We have a blog site and hosted it on a different domain but now we want to move to one place at our main site. now, we have challenges for displaying dynamic blogs on the gatsby site.

Finally, I found that gatsby provides support to render dynamic blogs as a static page. when build created that time fetch the blogs from the server and create a static page for all the blogs.

Gatsby is a very good platform and manages such a kind of thing easily.

So, I will show you how to create static pages from the API response into the Gatsby site.

Here are the steps you need to follow correctly.

Steps 1

Create a one blog file where you want to load a blog in your design.

For an ex. I created a file `blog/index.js` inside the component directory and the code looks like this,


Steps 2

Open a file `gatsby-node.js`

Declare the const for the API URL at the beginning of the file.

const blogURL = 'http://blog-api.com/api/posts';

We need to create an instance of the  `node-fetch` for fetching a data from API server.

const fetch = require(`node-fetch`);
Import the path for a resolve the page while creating a static page.
const path = require('path');
See the example how to create a static page from APIs. code look's like,
exports.createPages = (async ({graphql, actions}) => {
    const blogs = await fetch(blogURL);
    blogs.data.forEach((blog) => {
        createPage({
            path: 'blog/' + blog.slug,
            component: path.resolve(`./src/components/blog/index.js`),
            context: {
                // Data passed to context is available
                // in page queries as GraphQL variables.
                slug: blog.slug,
                blog: blog,
            },
        })
    })
Now we are done, and you can access blogpage via slug.


November 12, 20201 minuteauthorShailesh Ladumor
post

We have recently developed a site into the gatsby. We want to add Google Analytics to the website.

So, this is the way we implemented Google Analytics in the Gatsby site.

Use Gatsby Google GTag Plugin

Gatsby has a plugin gatsby-plugin-google-gtag that be used to easily add Google Global Site Tag to your Gatsby site.

Install the package by running the following command:

npm i gatsby-plugin-google-gtag --save

Configuration

Once the installation is complete, you can now add this plugin to your gatsby-config.js:

Configure trackingIds and other options. Add this into the plugins array. Like,

module.exports = {
  // ...
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
              // You can add multiple tracking ids and a pageview event will be fired for all of them.
              trackingIds: [
                "GA-TRACKING_ID", // Google Analytics / GA
                "AW-CONVERSION_ID", // Google Ads / Adwords / AW
                "DC-FLOODIGHT_ID", // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
              ],
              // This object gets passed directly to the gtag config command
              // This config will be shared across all trackingIds
              gtagConfig: {
                optimize_id: "OPT_CONTAINER_ID",
                anonymize_ip: true,
                cookie_expires: 0,
              },
              // This object is used for configuration specific to this plugin
              pluginConfig: {
                // Puts tracking script in the head instead of the body
                head: false,
                // Setting this parameter is also optional
                respectDNT: true,
                // Avoids sending pageview hits from custom paths
                exclude: ["/preview/**", "/do-not-track/me/too/"],
              },
      },
    },
  ],
}

This plugin automatically sends a “pageview” event to all products given as “trackingIds'' on every Gatsby's route change.

If you want to call a custom event you have access to window.gtag where you can call an event for all products.

Check out this code.

typeof window !== "undefined" && window.gtag("event", "click", { ...data })

NOTE: This plugin only works in production mode! To test your Global Site Tag is installed and

You need to run the following command for firing events correctly.

gatsby build && gatsby serve

If you need to exclude any path from the tracking system, you can add one or more to this optional array.

November 22, 20202 minutesauthorShailesh Ladumor
post

We have recently developed a site into the gatsby. Basically, the contact us feature is common on all websites. and we are implementing Mailchimp because it's a very popular platform in the email market. So, I will show you how to set up a Mailchimp on the Gatsby site.

Using gatsby-source-mailchimp

Use your Mailchimp API key to download your campaigns into Gatsby’s GraphQL data layer! Install the package by running the following command: npm i gatsby-source-mailchimp --save. How to configure Once the installation is complete, you can now add this plugin to your gatsby-config.js, like so: Configure mailchimp Key and add this {resolve: gatsby-source-mailchimp} into the plugins array. code looks like

module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-mailchimp',
      options: {
        // Avoid including your key directly in your file.
        // Instead, opt for adding them to .env files for extra
        // security ;)
        key: 'asd712jdas90122jdas90122jkadsd1-usXX',
        rootURL: 'https://usXX.api.mailchimp.com/3.0',
      },
    },
  ],
  // ...
}

This plugin was made out of a specific necessity, so it doesn't cover all of Mailchimp’s data sources, focusing only on campaigns.

This plugin provides few options. you can refer here

Using .env variables to hide your key

If you don’t want to attach your API key to the repo, you can easily store it in .env files by doing the following:

// In your .env file
MAILCHIMP_KEY = 'asd712jdas90122jdas90122jkadsd1-usXX';

// In your gatsby-config.js file
require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
});

module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-mailchimp',
      options: {
        key: process.env.MAILCHIMP_KEY,
        rootURL: '[https://usXX.api.mailchimp.com/3.0',](https://usxx.api.mailchimp.com/3.0%27,)
        // ...
      },
    },
  ],
  // ...
};
October 31, 20201 minuteauthorShailesh Ladumor
post

We are adding a sitemap in our all site pages for making sure search engines (such as Google) can find and crawl them all.

So, I will show you how to set a sitemap on the Gatsby site.

Using gatsby-plugin-sitemap

To generate an XML sitemap, you will use the gatsby-plugin-sitemap package.

Install the package by running the following command: npm install gatsby-plugin-sitemap

How to configure

Once the installation is complete, you can now add this plugin to your gatsby-config.js, like so:

Configure siteUrl and add this {resolve: gatsby-plugin-sitemap} into the plugins array. code looks like

module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {resolve: `gatsby-plugin-sitemap`},
  ],
}

Above is the minimal configuration required to have it work. By default, the generated sitemap will include all of your site’s pages.

You can exclude a path using the exclude option. you need to configure its

  • output (string) The file path and name. Defaults to /sitemap.xml.
  • exclude (array of strings) An array of paths to exclude from the sitemap.

code looks like,

module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {
    resolve: `gatsby-plugin-sitemap`,
    options: {
      output: `/some-other-sitemap.xml`,
        exclude: [`/category/*`, `/path/to/page`],
        }
    },
  ],
}

NOTE: This plugin only generates an output when run in production mode! To test your sitemap, run: gatsby build && gatsby serve

Now we are done and open the sitemap using your domain. for ex. https://abc.com/sitemap.xml

September 28, 20201 minuteauthorShailesh Ladumor
post

We work on projects with the admin panel every day. In which we mostly use data tables and we need to delete the record from the data table without page refresh.

So, today I will show you how to extract a record using Ajax. It's very easy to integrate.

Let's take one example. I have a Category data table and I want to delete one category from the table without refreshing the page. Now, what am I doing for that? First of all, I add a class for the listen to a click event into the delete button and it says delete-btn.

See the following image for where I added a class.

delete-record-using-ajax-in-laravel/1

I used SweetAlert for the confirmation popup. let add sweet alert's CSN into the index.blade.php.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css"> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

Let's declare routes of the delete record.

<script>let categoryUrl = '{{route('categories.index')}}'; </script>

Next steps, I'm going to listen to the click event of the delete button. one more thing does not forget to add the record id into the data attribute to the delete button. see the above image for it. I highlighted it with a yellow line.

So the general practices we use in Laravel is to write the following code to listen to a click event and delete a record,

$(document).on('click', '.delete-btn', function (event) {             
           const id = $(event.currentTarget).data('id');

  swal({ 
      title: 'Delete !',                     
      text: 'Are you sure you want to delete this Category" ?',                     
      type: 'warning',                    
      showCancelButton: true,                     
      closeOnConfirm: false,                     
      showLoaderOnConfirm: true,                     
      confirmButtonColor: '#5cb85c',                     
      cancelButtonColor: '#d33',                     
      cancelButtonText: 'No',                     
      confirmButtonText: 'Yes',                 },                 
          function () {                    
                   $.ajax({                 
                       url: categoryUrl + '/' + id,                 
                       type: 'DELETE',                 
                       DataType: 'json',                 
                       data:{"_token": "{{ csrf_token() }}"},                 
                       success: function(response){                     

                              swal({                                 
                                  title: 'Deleted!',                                 
                                  text: 'Category has been deleted.',                                 
                                  type: 'success',                                 
                                  timer: 2000,                             
                              });                     
 $('#categoryTbl').DataTable().ajax.reload(null, false);                 
              },                 
               error: function(error){                     
               swal({                                 
                   title: 'Error!',                                 
                   text: error.responseJSON.message,                                 
                   type: 'error',                                 
                   timer: 5000,                             
              })                     
            }             
        });                 
    });         
});

Now we are done with the front-end side and need to look into it backend side.

Let's declare the destroy method into the category Controller. I hope are you generate crud with InfyOm Laravel Generator. so, the Destroy method and routes are there. If not please create a route. if the destroy method is there then need to change the response of that method.

The destroy method code looks like,

public function destroy($id) { $category = $this->categoryRepository->find($id); if (empty($category)) { Flash::error('Category not found');

        return $this->sendError('Category not found.');
    }

    $this->categoryRepository->delete($id);

    return $this->sendSuccess('Category deleted successfully.');
}

Now we are done. the video tutorial also available here

August 19, 20202 minutesauthorShailesh Ladumor
post

The OneSingnal is the market leader in push notification providers. It provides mobile + web push, email & in-app messages, and an easy way to send notifications. OneSignal provides official core PHP APIs but not the Laravel package. We are using OneSignal in many projects and write a bunch of line code in all projects where we needed OneSingnal.

One day I had an idea in my mind why I should not write a Laravel wrapper for OneSignal?. Finally, I wrote the shailesh-ladumor/one-signal Laravel Wrapper for it. Using this package, we can write neat & clean code and just a few lines of code.

OneSignal add this package in his docs here, and watch the video tutorial here.

This package also works with the previous Laravel version.

Today we are going to see how we can use Laravel OneSignal Wrapper in Laravel. Let's see step by step, how we can do that.

Install Packages

Install shailesh-ladumor/one-signal by the following command,

composer require ladumor/one-signal

Publish the config file

Run the following command to publish config file,

php artisan vendor:publish --provider="Ladumor\OneSignal\OneSignalServiceProvider"

Add Provider

Add the provider to your config/app.php into provider section if using lower version of Laravel,

Ladumor\OneSignal\OneSignalServiceProvider::class

Add Facade

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

'OneSignal' => \Ladumor\OneSignal\OneSignal::class

Configure a .env file with following keys

ONE_SIGNAL_APP_ID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX 
ONE_SIGNAL_AUTHORIZE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X 
ONE_SIGNAL_AUTH_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

ONE_SIGNAL_AUTH_KEY is optional if you do not want to create an app. I hope you are familiar with the OneSignal Platform and know how to get APP_ID and AUTHORIZE. If not, you should see the below image for how to get it.

onesignal-in-laravel/1

So, we are done. Let's check how to send push notifications.

Check out this code to send a push notification.

use Ladumor\OneSignal\OneSignal; 
$fields['include_player_ids'] = ['xxxxxxxx-xxxx-xxx-xxxx-yyyyy'] 
$message = 'hey!! This is a test push.!' OneSignal::sendPush($fields, $message);

Video tutorial also available here

July 02, 20202 minutesauthorShailesh Ladumor