SlideShare a Scribd company logo
How to Build
Laravel
Package
Using
Composer?
https://www.bacancytechnology.com
Introduction
A Laravel package is a set of reusable classes
that improve the functionality of a Laravel
website. To put it another way, a package is
what WordPress plugins are. Laravel
packages are designed to reduce
development time by encapsulating
reusable functionality in a set of stand-
alone classes that can be used in any Laravel
project.


In this tutorial: How to Build Laravel
Package using Composer, we’ll construct a
Laravel package for a contact form. Let’s get
this party started.
Prerequisite to
Build Laravel
Package using
Composer
Laravel v 5.5 or above is required.
Composer installed on your system. You
may get Composer here if you don’t
already have it.
Here are the prerequisites to build Laravel
package using Composer:
Basic Set-Up and
Installation
Because a package is designed to give more
functionality to a Laravel website, the first
step is to construct a Laravel website. We’ll
use Composer to set it up. Check out the
official Laravel documentation for more
installation options.
$ composer create-project —prefer-dist
laravel/laravel packagetestapp
You’ll need to configure your env file and
specify your app key and other relevant
data after that’s done. Use the following
command in your terminal or manually
transfer the contents of the .env.example to
a new file and save it as .env.
$ cp .env.example .env
$ php artisan key:generate
Once done, use the below command.
Your .env should look like this once you’ve
generated your app key and configured
your database details
Our basic Laravel app is now set up. It’s
time to start working on our package.
Develop high-performance Laravel
applications with Bacancy!
Hire Laravel Developer and witness the
building of your dream product with us. We
have dedicated developers with
extraordinary problem skills. Contact us
today!
Project Structure
Manually generating individual files and
folders
Utilizing a package such as this CLI
utility.
We’ll set up the fundamental essentials of
our package. There are essentially two
methods for accomplishing this:


Here, we will manually generate the files
and directories to understand how each
component fits together.


Here is our package’s folder structure.


Create folders with the following structure
from your root directory.


$ packages/YourVendor/YourPackage/
Because it’s not a good practice to update
the code in the vendor folder, we’ll perform
all of our work outside in the
packages/YourVendor/YourPackage/
directory instead of
vendor/YourVendor/YourPackage/.


When we’re finished releasing our package,
it’ll be available for download under the
vendor folder.


YourVendor is the name of the vendor,
which might be your name or the name of
the customer or business for whom you are
generating the package
.
The package name is represented by
YourPackage. It will be contactform in our
instance.
Let’s begin creating the files and folders
that will comprise our package.
YourVendor
└──contactform
└──src
├──Database
│ └──migrations
├──Http
│ └──controllers
├──Models
├──resources
│ └──views
└──routes
Create Composer File
We’ll initialize the Composer now. Use the
below command to generate composer.json
$ composer init
Because it is interactive, it will ask you a
series of questions to fill up your
composer.json file. If you’re unsure, click
enter to use the default response; if you’re
not sure, you may update it later directly
from the composer.json file.
The composer.json file should now look like
this.
{
"name": "YourVendor/Contactform",
"description": "A contact form package
for laravel",
"authors": [{
"name": "Usama Patel",
"email": "john.doe@email.com"
}],
"require": {}
}


We need to inform composer.json to
autoload our files, so add this code to your
composer.json.
"autoload": {
"psr-4": {
"YourVendorcontactform": "src/"
}
}
Our composer.json file should now look
something like this.
{
"name": "YourVendor/Contactform",
"description": "A contact form package
for laravel",
"authors": [{
"name": "Usama Patel",
"email": "john.doe@email.com"
}],
"require": {},
"autoload": {
"psr-4": {
"YourVendorContactform": "src/"
}
}
}
Create an empty git repository to keep
track of modifications after that (we’ll add
the remote repo later). Use the below
command.
$ git init
Create Service
Provider
Let’s start by adding some files to our
package. To begin, we must identify a
service provider for our package. Laravel
utilizes a service provider to figure out
which files will be loaded and accessible by
your package.
Create a ContactFormServiceProvider.php
file in your src/subdirectory
$ src/ContactFormServiceProvider.php
We need to define a few items within our
service provider:
1. The namespace (which we defined in
our composer.json autoload).
2. The extension (the Laravel class which
our service provider extends)
3. The two mandatory methods that every
service provider must have (at least two
methods are required for every Laravel
package service provider: boot() and
register()).
Add the following lines of code to your
service provider class.
Note: You may replace YourVendor with
your own vendor name in the code below.


// ContactFormServiceProvider.php


<?php namespace
YourVendorcontactform; use
IlluminateSupportServiceProvider; class
ContactFormServiceProvider extends
ServiceProvider { public function boot() { }
public function register() { } } ?>
We need to inform Laravel how to load our
package and utilize its functionalities
because we haven’t deployed it and it isn’t
yet within our vendor folder, so inside the
root of your Laravel project in the
composer. Add the following code to your
JSON.
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"YourVendorContactform":
"packages/YourVendor/contactform/src",
"App": "app/"
}
},
"autoload-dev": {
"psr-4": {
"YourVendorContactform":
"packages/YourVendor/contactform/src",
"Tests": "tests/"
}
},


Depending on your Laravel version, Laravel
may add it for you automatically. If it does,
be sure to skip it.
Then, on your terminal, run the following
command at the root of your app.
$ composer dump-autoload
Let’s check to verify if our package is loaded
appropriately now. Let’s create a route and
load it in the startup method of the
ContactFormServiceProvider.php file
// ContactFormServiceProvider.php
$this-
>loadRoutesFrom(__DIR__.'/routes/web.
php');
The current directory where the file is
located is referred to as __DIR__.
The routes folder we’ll construct for our
package, which will exist in our src
folder, not the default Laravel routes, is
referenced in routes/web.php.
Please take notice of the following:
Add the following code to the web.php file
in our package routes folder.
<?php //
YourVendorcontactformsrcroutesweb.
php Route::get('contact', function(){ return
'Hello from the contact form package'; }); ?
>
Then, in our root config/app.php, we need
to add our new service provider to the
providers’ array as shown below.
// config/app.php
'providers' => [
...,
AppProvidersRouteServiceProvider::cla
ss,
// Our new package class
YourVendorContactformContactFormS
erviceProvider::class,
],
Run the App
php artisan serve
Start your Laravel app now by using the
command.
Go to localhost:8000/contact in your
browser and you should see something
like this:
You might want to know
Top Laravel Packages To Install
Github
Repository:
Laravel Package
Example
Now we know our package is loading
properly we need to create our contact
form. You can find the rest of the code on
this Github Repository.
Conclusion
This was a basic tutorial to get started with
how can you build Laravel package using
Composer. With your newfound
understanding, you can create even more
amazing packages.
Thank you
https://www.bacancytechnology.com

More Related Content

PDF
What's New In Laravel 5
PPTX
What-is-Laravel-23-August-2017.pptx
PDF
Laravel intake 37 all days
PPTX
Lecture 2_ Intro to laravel.pptx
PPTX
Laravel
PPT
Bridging the Gap - Laracon 2013
PDF
Top laravel packages to install handpicked list from expert
PPTX
What-is-Laravel and introduciton to Laravel
What's New In Laravel 5
What-is-Laravel-23-August-2017.pptx
Laravel intake 37 all days
Lecture 2_ Intro to laravel.pptx
Laravel
Bridging the Gap - Laracon 2013
Top laravel packages to install handpicked list from expert
What-is-Laravel and introduciton to Laravel

Similar to How to Build Laravel Package Using Composer.pdf (20)

PDF
composer_talk_20160209
PDF
Why Laravel?
PDF
Laravel 4 presentation
PDF
How to Create REST API Using Laravel Framework
PDF
Building RESTful APIs with Laravel A Complete Guide.pdf
PDF
Introduction to Laravel
PDF
MidwestPHP 2016 - Adventures in Laravel 5
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
PPT
Web service with Laravel
PDF
Getting to know Laravel 5
PDF
An Introduction to the Laravel Framework (AFUP Forum PHP 2014)
PDF
Web services with laravel
PDF
Laravel presentation
PDF
SDPHP Lightning Talk - Let's Talk Laravel
PPTX
Introduction to Laravel Framework (5.2)
PDF
Laravel Package Development Best Practices Updated for 2025.pdf
PPTX
Laravel 5
PPT
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
PDF
Laravel 4 package development
PDF
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
composer_talk_20160209
Why Laravel?
Laravel 4 presentation
How to Create REST API Using Laravel Framework
Building RESTful APIs with Laravel A Complete Guide.pdf
Introduction to Laravel
MidwestPHP 2016 - Adventures in Laravel 5
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Web service with Laravel
Getting to know Laravel 5
An Introduction to the Laravel Framework (AFUP Forum PHP 2014)
Web services with laravel
Laravel presentation
SDPHP Lightning Talk - Let's Talk Laravel
Introduction to Laravel Framework (5.2)
Laravel Package Development Best Practices Updated for 2025.pdf
Laravel 5
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel 4 package development
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Ad

More from Katy Slemon (20)

PDF
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
PDF
Data Science Use Cases in Retail & Healthcare Industries.pdf
PDF
How Much Does It Cost To Hire Golang Developer.pdf
PDF
What’s New in Flutter 3.pdf
PDF
Why Use Ruby On Rails.pdf
PDF
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
PDF
How to Implement Middleware Pipeline in VueJS.pdf
PDF
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
PDF
How to Develop Slack Bot Using Golang.pdf
PDF
IoT Based Battery Management System in Electric Vehicles.pdf
PDF
Understanding Flexbox Layout in React Native.pdf
PDF
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
PDF
New Features in iOS 15 and Swift 5.5.pdf
PDF
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
PDF
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
PDF
Flutter Performance Tuning Best Practices From the Pros.pdf
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
PDF
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
PDF
Ruby On Rails Performance Tuning Guide.pdf
PDF
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
How Much Does It Cost To Hire Golang Developer.pdf
What’s New in Flutter 3.pdf
Why Use Ruby On Rails.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
How to Develop Slack Bot Using Golang.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Understanding Flexbox Layout in React Native.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
New Features in iOS 15 and Swift 5.5.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Ruby On Rails Performance Tuning Guide.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Ad

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation theory and applications.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
A Presentation on Artificial Intelligence
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
KodekX | Application Modernization Development
Teaching material agriculture food technology
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
NewMind AI Weekly Chronicles - August'25 Week I
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Monthly Chronicles - July 2025
Encapsulation theory and applications.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
A Presentation on Artificial Intelligence
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KodekX | Application Modernization Development

How to Build Laravel Package Using Composer.pdf

  • 3. A Laravel package is a set of reusable classes that improve the functionality of a Laravel website. To put it another way, a package is what WordPress plugins are. Laravel packages are designed to reduce development time by encapsulating reusable functionality in a set of stand- alone classes that can be used in any Laravel project. In this tutorial: How to Build Laravel Package using Composer, we’ll construct a Laravel package for a contact form. Let’s get this party started.
  • 5. Laravel v 5.5 or above is required. Composer installed on your system. You may get Composer here if you don’t already have it. Here are the prerequisites to build Laravel package using Composer:
  • 7. Because a package is designed to give more functionality to a Laravel website, the first step is to construct a Laravel website. We’ll use Composer to set it up. Check out the official Laravel documentation for more installation options. $ composer create-project —prefer-dist laravel/laravel packagetestapp You’ll need to configure your env file and specify your app key and other relevant data after that’s done. Use the following command in your terminal or manually transfer the contents of the .env.example to a new file and save it as .env. $ cp .env.example .env
  • 8. $ php artisan key:generate Once done, use the below command. Your .env should look like this once you’ve generated your app key and configured your database details
  • 9. Our basic Laravel app is now set up. It’s time to start working on our package. Develop high-performance Laravel applications with Bacancy! Hire Laravel Developer and witness the building of your dream product with us. We have dedicated developers with extraordinary problem skills. Contact us today!
  • 11. Manually generating individual files and folders Utilizing a package such as this CLI utility. We’ll set up the fundamental essentials of our package. There are essentially two methods for accomplishing this: Here, we will manually generate the files and directories to understand how each component fits together. Here is our package’s folder structure. Create folders with the following structure from your root directory. $ packages/YourVendor/YourPackage/
  • 12. Because it’s not a good practice to update the code in the vendor folder, we’ll perform all of our work outside in the packages/YourVendor/YourPackage/ directory instead of vendor/YourVendor/YourPackage/. When we’re finished releasing our package, it’ll be available for download under the vendor folder. YourVendor is the name of the vendor, which might be your name or the name of the customer or business for whom you are generating the package . The package name is represented by YourPackage. It will be contactform in our instance. Let’s begin creating the files and folders that will comprise our package.
  • 15. We’ll initialize the Composer now. Use the below command to generate composer.json $ composer init Because it is interactive, it will ask you a series of questions to fill up your composer.json file. If you’re unsure, click enter to use the default response; if you’re not sure, you may update it later directly from the composer.json file. The composer.json file should now look like this.
  • 16. { "name": "YourVendor/Contactform", "description": "A contact form package for laravel", "authors": [{ "name": "Usama Patel", "email": "john.doe@email.com" }], "require": {} } We need to inform composer.json to autoload our files, so add this code to your composer.json. "autoload": { "psr-4": { "YourVendorcontactform": "src/" } }
  • 17. Our composer.json file should now look something like this. { "name": "YourVendor/Contactform", "description": "A contact form package for laravel", "authors": [{ "name": "Usama Patel", "email": "john.doe@email.com" }], "require": {}, "autoload": { "psr-4": { "YourVendorContactform": "src/" } } }
  • 18. Create an empty git repository to keep track of modifications after that (we’ll add the remote repo later). Use the below command. $ git init
  • 20. Let’s start by adding some files to our package. To begin, we must identify a service provider for our package. Laravel utilizes a service provider to figure out which files will be loaded and accessible by your package. Create a ContactFormServiceProvider.php file in your src/subdirectory $ src/ContactFormServiceProvider.php We need to define a few items within our service provider: 1. The namespace (which we defined in our composer.json autoload). 2. The extension (the Laravel class which our service provider extends) 3. The two mandatory methods that every service provider must have (at least two methods are required for every Laravel package service provider: boot() and register()).
  • 21. Add the following lines of code to your service provider class. Note: You may replace YourVendor with your own vendor name in the code below. // ContactFormServiceProvider.php <?php namespace YourVendorcontactform; use IlluminateSupportServiceProvider; class ContactFormServiceProvider extends ServiceProvider { public function boot() { } public function register() { } } ?>
  • 22. We need to inform Laravel how to load our package and utilize its functionalities because we haven’t deployed it and it isn’t yet within our vendor folder, so inside the root of your Laravel project in the composer. Add the following code to your JSON. "autoload": { "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "YourVendorContactform": "packages/YourVendor/contactform/src", "App": "app/" }
  • 23. }, "autoload-dev": { "psr-4": { "YourVendorContactform": "packages/YourVendor/contactform/src", "Tests": "tests/" } }, Depending on your Laravel version, Laravel may add it for you automatically. If it does, be sure to skip it. Then, on your terminal, run the following command at the root of your app. $ composer dump-autoload
  • 24. Let’s check to verify if our package is loaded appropriately now. Let’s create a route and load it in the startup method of the ContactFormServiceProvider.php file // ContactFormServiceProvider.php $this- >loadRoutesFrom(__DIR__.'/routes/web. php'); The current directory where the file is located is referred to as __DIR__. The routes folder we’ll construct for our package, which will exist in our src folder, not the default Laravel routes, is referenced in routes/web.php. Please take notice of the following:
  • 25. Add the following code to the web.php file in our package routes folder. <?php // YourVendorcontactformsrcroutesweb. php Route::get('contact', function(){ return 'Hello from the contact form package'; }); ? > Then, in our root config/app.php, we need to add our new service provider to the providers’ array as shown below.
  • 26. // config/app.php 'providers' => [ ..., AppProvidersRouteServiceProvider::cla ss, // Our new package class YourVendorContactformContactFormS erviceProvider::class, ],
  • 28. php artisan serve Start your Laravel app now by using the command. Go to localhost:8000/contact in your browser and you should see something like this: You might want to know Top Laravel Packages To Install
  • 30. Now we know our package is loading properly we need to create our contact form. You can find the rest of the code on this Github Repository.
  • 31. Conclusion This was a basic tutorial to get started with how can you build Laravel package using Composer. With your newfound understanding, you can create even more amazing packages.