MotleyFool TMOT 2c201c94 porch package

How to Develop a Package in Laravel?

We use packages in Laravel everyday. But few of us never tried to develop their own packages in Laravel. Today we are trying to make our own package in Laravel.

1. Setting Up Laravel project

First we need to install Laravel 8 by running this command.

composer create-project laravel/laravel shop-app

2. Setting Up Directory Structure

Now suppose we are creating package for Shop app for Laramatic tutorial. Create laramatic/shop/src directory into root.

3. Initiating Composer

Now run following command in src to initiate Composer.

composer init

Once we have full information we will get this output on our command line. This is just easy.

composer image 1

4. Add Configuration

Now create laramatic/shop/src/config/shop.php file and add this code there.

return [
	'api_key'    => env( 'SHOP_API_KEY' ),
	'api_secret' => env( 'SHOP_API_SECRET' ),
	'api_url'    => env( 'SHOP_API_URL' )
];

This will help us to use environment variables in our code.

5. Add Service Provider

Now you can create Service Provider in laramatic/shop/src/ShopServiceProvider.php and copy following code there.

namespace Laramatic\Shop;

use Illuminate\Support\ServiceProvider;

class ShopServiceProvider extends ServiceProvider {
	/**
	 * Register any application services.
	 *
	 * @return void
	 */
	public function register() {
		parent::register();
	}

	/**
	 * Bootstrap any application services.
	 *
	 * @return void
	 */
	public function boot() {
		$this->publishes( [
			__DIR__ . '/../config/shop.php' => config_path( 'shop.php' )
		], 'shop' );
	}
}

This code will publish configuration for our package. We can use it to publish migrations and many other tasks.

6. Add Product file

Now we will add Product.php file in src folder. This file contains methods which we will use in our code if we have created this package.

namespace Laramatic\Product;

class Product {

	public function testShopPackage() {
		echo "our package is working fine";
	}
}

7. Update Composer file

Now we will update our composer.json file accordingly. Add this code in your composer file.

"require": {},
  "autoload": {
    "Laramatic\\Shop\\": "src/"
  },
  "extra": {
    "laravel": {
      "providers": [
        "Laramatic\\Shop\\ShopServiceProvider"
      ]
    }
  }

Your composer.json should look like this.

composer 2

8. Update main Composer file

Now add following code in main composer file in root.

"repositories": [
    {
      "type": "path",
      "url": "laramatic/shop",
      "options": {
        "symlink": true
      }
    }
  ],
  "license": "",
  "require": {
    "laramatic/shop": "dev-develop"
  }