Magento 2 custom shipping method

I am creating here Magento 2 off-line custom shipping method. It is pretty simple as we just need to follow the steps done by core developers for the core module vendor/magento/module-offline-shipping. There are four off-line shipping methods available in this module which are flat rate, free shipping, pickup and table rates.

Let’s start step by step…

For every new module in Magento 2, We need to take care of three files for register a module.

app/code/Namespace/Module/etc/module.xml

app/code/Namespace/Module/registration.php

app/etc/config.php

Step 1 : I am taking a module name as Akh_CustomShipping.

Create a file on path app/code/Akh/CustomShipping/etc/module.xml and add below content of code.

Above line will define the module name and module setup version.

Step 2 : Create a new file called registration.php on the path below.

app/code/Akh/CustomShipping/registration.php  and add below code in it.

This is a common code which we need to write in this file while creating every new module in Magento 2. We just need to change module name every time. In my case it is Akh_CustomShipping here.

Step 3 : Now we need to enabled the module in the file app/etc/config.php

We can do it by either adding module name manually in this file as shown below.

Or just run below command from Magento root directory in terminal. It will automatically do new entry of the module in this file.

Same way we can disable the module by running the command below.

We can check the status of every modules by running command below.

Step 4 : Let’s create a config.xml file of the module which defines the carrier configuration of the shipping method.

Create a file on path app/code/Akh/CustomShipping/etc/config.xml and the below content of code in it.

This line will define the model class of the shipping carrier which we will create in further step.

Step 5 : Now create a system.xml file, which will create a all system configuration fields in admin for the shipping method.

Create a file on path app/code/Akh/CustomShipping/etc/adminhtml/system.xml and add below code in it.

Above code will create a new configuration in admin section under Store -> Settings -> Configuration -> Sales -> Shipping Methods -> Custom Shipping.

Step 6 : Let’s create a final model class of the shipping carrier.

Create a file on path app/code/Akh/CustomShipping/Model/Carrier/Custom.php and add below code in it.

collectRates function will calculate and return the shipping charges based on system configuration settings done for the shipping method.

Now when we run the site in browser it will show below error on page or in var/report file

Just run the command in terminal as mention in error and check site again.

Hope this will give some idea!!