Laravel Posts
SMS Driver with Laravel Facades and Service ProvidersLaravel

SMS Driver with Laravel Facades and Service ProvidersLaravel
In the previous article, we learned How to create Laravel Facade and how it can help to simplify our code and make it more accessible and beautiful.
In this article, we will see how we can control our SMS Provider/Gateway via configuration without even touching the code and changing it from the environment directly.
Use Case
Imagine you have two SMS Providers called ABC and XYZ that you are using in our application. But you need to switch it over time. But the trick is, you do not want to change your code when you change to another SMS service provider. Just like when you change any driver in a Laravel App like Log, Cache, Queue, Database, etc.
So let's figure out how to do that.
Solution
Create SMS Service Contract
Create an SMS Service contract interface that contains the method to send the SMS.
Create a class app/Services/Contracts/SMSServiceContract.php
with the following content,
<?php
namespace App\Services\Contracts;
interface SMSServiceContract
{
public function sendSMS($phone, $message);
}
The purpose of this class is, every SMS Service should implement this interface and it should have at least one method sendSMS
with the same parameters.
Create SMS Service Implementations
The second step is to create the real implementation of our SMS Services which will be responsible for sending the SMS.
So as we have two SMS services, we will create two classes,
ABC SMS Service
Create a class app/Services/ABCSMSService.php
with the following content,
<?php
namespace App\Services;
class ABCSMSService implements SMSServiceContract
{
public function sendSMS($phone, $message)
{
// Code here to call API of ABC SMS Provider to send SMS
}
}
XYZ SMS Service
Create a class app/Services/XYZSMSService.php
with the following content,
<?php
namespace App\Services;
class XYZSMSService implements SMSServiceContract
{
public function sendSMS($phone, $message)
{
// Code here to call API of XYZ SMS Provider to send SMS
}
}
Create Facade to Send SMS
The third step is to create a Facade to send an SMS. Create a facade class app/Facades/SMSGateway.php
with the following content,
<?php
namespace App\Facades;
use App\Services\Contracts\SMSServiceContract;
use Illuminate\Support\Facades\Facade;
class SMSGateway extends Facade
{
/**
Get the registered name of the component.
@return string
/
protected static function getFacadeAccessor()
{
return SMSServiceContract::class;
}
}
Here, note that we are giving SMSServiceContract
class name as a facade assessor. So we will need to use that same class name while binding it to the real implementation in our service provider.
Define SMS Driver in config
We need to define our SMS Driver into our config file. You can create a new config file or can use config/services.php
. To keep it simple, we will define it in services.php. I will add the following content at the end of the file before the closing bracket. so it will look like something,
<?php
return [undefined]
Define your driver in .env file
Update your .env
file and add SMS_SERVICE
variable, something like
SMS_SERVICE=abc
Create/Modify Service Provider
The final step here is, we need to either create our own service provider and add it to config/app.php
or we can use AppServiceProvider.php
as well. To keep it simple let's add it to AppServiceProvider.
In app/Providers/AppServiceProvider.php
we will add the following code under the register
method,
$this->app->bind(SMSServiceContract::class,
function ($app)
{
if (config('services.sms') == 'abc')
{
return new ABCSMSService();
} else {
return new XYZSMSService();
}
});
Note: Do not forget to import all these classes at the top.
And that's it.
Usage
Now you can use your Facade to send the SMS.
\App\Facades\SMSGateway::sendSMS($phoneNumber, $message);
Or if you made an alias,
\SMSGateway::sendSMS($phoneNumber, $message);
Change service provider
Now if you want to change your service provider, all you need to do is, just go to the .env
and change the provider to xyz
and it will use the XYZSMSService
class to send the SMS.
I hope this will help to understand Laravel Service Providers and Facade in a much better way.
Laravel UPCItemDB PackageLaravel

Laravel UPCItemDB PackageLaravel
We have been working on an inventory system for one of our clients for a long time and recently, what we needed was to retrieve inventory item information by UPC code or ISBN or EAN. so the end customer does not need to fill a full form with all the details.
We implemented a feature where customers can just enter or scan UPC/ISBN/EAN code on the mobile app and we retrieve all the information of the product and auto-fill it with an image of the product as well.
So we started using UPCItemDB which has a very nice database of items. You can call their API and retrieve information about the product by sending UPC code. It has a free plan that you can use for trial purposes.
But there was no proper PHP or Laravel package for that, so we decided to make our own and publish it to Github.
It's called laravel-upcitemdb
and here is the link for it: https://github.com/InfyOmLabs/laravel-upcitemdb
Here are the installation steps and how to use this package.
Installation
Install the package by the following command,
composer require infyomlabs/laravel-upcitemdb
Publish the config file
Run the following command to publish config file,
php artisan vendor:publish --provider="InfyOm\UPCItemDB\UPCItemDBServiceProvider"
Add Facade
Add the Facade to your config/app.php
into aliases
section,
'UPCItemDB' => \InfyOm\UPCItemDB\UPCItemDB::class,
Usage
Lookup
For UPC Lookup, use the lookup method by calling,
\UPCItemDB::lookup('4002293401102');
Search
For Search API, you can use the search method,
\UPCItemDB::search('iphone 6');
\UPCItemDB::search('iphone 6', ['brand' => 'apple']);
How to Create Laravel Facade and Simplify CodeLaravel

How to Create Laravel Facade and Simplify CodeLaravel
Last month, I started training in one company where I am giving Laravel Training to around 15-20 PHP Developers, where we discussed the core Laravel concepts to them including Service Providers, Facades, Eloquent, and many more.
There I explained to them the use and beauty of Laravel Facades and how the use of Facade can simplify code. We took a real practical example and use case they have, which I'm outlining here.
Use Case
They are building a CRM application and using some third party API to send an SMS. Though Laravel Notification Channels are the best way to send the SMS but here that's not the goal of this post, so we will try to stick to the Facade development to send the SMS.
Here is how we were sending SMS so far.
Traditional way
Have one common Class/Repository/Manager called SMSManager
.
<?php
namespace App\Managers;
class SMSManager
{
public function sendSMS($recipient, $message)
{
// code to send sms
}
}
This code and pattern look completely fine. But the problem was every time when we needed to send an SMS they needed to either Create/Inject SMSManager
class and call sendSMS
method of it.
Parsedown | the parser that we created ... $smsManager = new SMSManager(); $smsManager->sendSMS($phoneNumber, $message); ... Parsed in 0.13 ms or 1 times faster
...
$smsManager = new SMSManager();
$smsManager->sendSMS($phoneNumber, $message);
...
Also, this code is not scalable. If you want to change your SMS Provider then you need to replace the function or create a new function. Or you want to use multiple SMS Providers for different users based on their subscription then this way doesn't work.
Laravel Facade Way
Laravel Facades is a great way to call static interfaces of the classes. So you don't need to make/inject SMSManager
class instance and you can directly call sendSMS
function.
To do that, we need to create Facade class and bind its accessor in Service Provider. We can create our own service provider or even can do it in AppServiceProvider
as well. To keep it simple, let's use AppServiceProvider
as of now.
Create a Facade Class
Create a new class called SMSGateway
into app\Facades
directory with the following code,
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class SMSGateway extends Facade
{
/**
Get the registered name of the component.
@return string
/
protected static function getFacadeAccessor()
{
return 'sms_gateway';
}
}
Bind Facade with SMSManager Implementation
The next step is to bind our facade class with our real SMSManager
implementation. To do that, open AppServiceProvider
and add the following line to the register
method,
$this->app->bind('sms_gateway', function ($app) {
return new SMSManager();
});
Now, we are all set to use our Facade in our code.
Usage of Facade in code
To send an SMS, we now no longer need to create instance of SMSManager
, we can directly use,
\App\Facades\SMSGateway::sendSMS($phoneNumber, $message);
Make Alias (Optional)
Or, you can add this facade to config/app.php
into aliases
section,
'SMSGateway' => App\Facades\SMSGateway::class,
And you can directly call,
\SMSGateway::sendSMS($phoneNumber, $message);
So this way, we can clean out our code and utilize the Laravel Facade to make our code more beautiful.
Hope this helps.
Laravel App - Code Optimizations TipsLaravel

Laravel App - Code Optimizations TipsLaravel
Last month we started working on one of our internal project called InfyTracker, which we were planning to use as a simple time tracker and very little of project management or task reporting.
We have also published it as an open source project to our Github account so other people from the community can use it. It's still in alpha stage and we are still working on it and making tons of improvements. But, While building this project, we found a few things that we think might be useful to optimize the app or can be used in other projects. Also, I think lots of developers even do not realize these things.
So I planned to share it with the community where I will be discussing them in a detail with solutions we used. So here are the things/mistakes that we found during our project development.
- Adding all stylesheets and scripts in a layout file
- Not separating out page level CSS or JS
- Not using laravel-mix
1. Adding all stylesheets and scripts in layout
What I've seen is, when we want to add a new library/package to the project, people generally go to the layout file and just insert a style and script tag there.
For e.g., I want to use moment-js in the app, so what I do, I go to my layout file and include moment-js script tag there via CDN. Even if I only need moment-js in few of my pages. same can be there for other libraries like datatables, even if we only need datatables in a few pages of the app.
The problem it creates is, even if we don't need them in most of our pages, those files are still included in our page and of course, the page takes more time to load.
2. Not separating out page level CSS or JS
Generally, we use lots of JS in our code. And for all page level JS/CSS, most of the developers put it in a blade file of the page at the bottom with some section of JS/CSS.
For e.g, I have used a datatable in my page, so I need to initialize the datatable. so generally, I will have declared one section called scripts or bottom_js which will be yielded in my layout file. That's what I have seen in lots of code.
But, there are two problems with that,
- When that page is loaded, your JS code is completely visible to the world and sometimes that's not good and secure
- It's not minified (and since it's sitting into your blade files, there is no way to minify it either)
3. Not using laravel-mix
In really few projects or very few expert developers use laravel-mix or use laravel-mix in the right way. When you do not use laravel-mix in your site, your JS/CSS files are not minified. It's completely visible to the world which can be sometimes dangerous and file sizes are big as well in large projects.
That's the three major things that we found while developing this project.
Here is the solution that we used to overcome these problems.
Solution 1. Adding all stylesheets and scripts in specific pages
To resolve this problem, we declared two sections in our layout file.
- stylesheets
- scripts
so all of our web pages which has a dependency for the third-party CSS/JS libraries will look like following,
@extends('layouts.app')
@section('stylesheets')
<link rel="stylesheet" href="https://rawgit.com/fronteed/iCheck/1.x/skins/all.css">
@endsection
@section('content')
....content here....
@endsection
@section('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/iCheck/1.0.2/icheck.min.js"></script>
@endsection
As per the above example, the iCheck library will be only added on pages where we are actually using iCheck instead of all of my web pages.
Solution 2. Separating out page level CSS or JS
To resolve this problem, we also declared two new sections in the layout file.
- page_css
- page_js
page_css section will contain page level CSS and page_js section will contain page level javascript like initializing datatable or checkboxes etc. Also, all page level CSS and JS are not placed directly inside the blade file. But we go one step further.
Under the resources/assets folder, we have two folders,
- js - contains all page level JS for different blade files
- styles - contains all page level CSS for different blade files
We tried to follow the same folder structure for this that we used for our blade views.
If you have multiple files then you can try to use names like index.js, edit.js, etc, just the same as your blade view names.
And in your blade view files, you can include them as a script or stylesheet. For e.g.
@section('page_js')
<script src="{{ mix('assets/js/task/task.js') }}"></script>
@endsection
Note: Use of mix is explained in the next section. so you can just ignore that as of now. But the basic idea is, include them as a script or stylesheet with sections, instead of directly putting them in blade files.
Solution 3. Using laravel-mix
Laravel mix is a great tool for asset compilation. All of the page level JS/CSS files and other common JS/CSS should be compiled by laravel mix and should be copied to the public folder with versioning for cache busting. And then it will be included via mix helper in our blade views. (As explained in the above solution at the bottom of the section).
For e.g. our webpack.mix.js looks like the following,
/* CSS */
mix.sass('resources/assets/style/sass/laravel/app.scss', 'public/assets/style/css/app.css')
.sass('resources/assets/style/sass/style.scss','public/assets/style/css/style.css')
.sass('resources/assets/style/sass/dashboard.scss','public/assets/style/css/dashboard.css')
.version();
/* JS */
mix.js('resources/assets/js/custom.js','public/assets/js/custom.js')
.js('resources/assets/js/users/user.js','public/assets/js/users/user.js')
.js('resources/assets/js/task/task.js','public/assets/js/task/task.js')
.version();
This will minify our code and make it secure in the production environment.
Hope this helps.
How to display relationship data into Yajra DataTables with InfyOm Laravel GeneratorLaravel

How to display relationship data into Yajra DataTables with InfyOm Laravel GeneratorLaravel
Lots of people asked a question on our Github Repo about how they can display relationship data into index while using Datatables. so I decided to write a post with a detailed tutorial on that. Let's see how it's possible.
Problem:
Let's imagine the following simple scenario. We have a users table and we have a posts table. Post table is pretty simple with the following fields:
- id
- author_id
- title
- body
- created_at
- updated_at
Where author_id is a foreign key to the users table. We want to display the author name into the index table.
But since we need that data from the relationship, there is no direct way to display that into Datatable.
Solution:
Let's perform the following steps (before performing these steps, generate your CRUD with datatables for Post model):
Step 1: Add author relationship into Post model
Since we want to display the author name of the post, let's add author relationship into Post.php
public function author() {
return $this->belongsTo(User::class, 'author_id');
}
Step 2: Modify PostDataTable
Since we have to display relationship data we need to load it using eager loading of laravel. Modify the query method of PostDataTable.php. something like,
public function query(Post $model) {
return $model->newQuery()->with(['author']);
}
Also, we need to add one more column author name into the datatable. so modify getColumns method and add that to the array. something like,
protected function getColumns() {
return [
'title',
'author_name' => new \Yajra\DataTables\Html\Column([
'title' => 'Author Name',
'data' => 'author.name',
'name' => 'author.name'
])
];
}
This will add one more column with header "Author Name" in the datatable before "Action" column. Here, we are adding custom datatable column where key will the name of column which datatable use internally, title will be used for Datatable Column header title and data will be used for retrieving data.
And that's it. Run your code and you should be able to see Author name of the post into your datatable.
How to use Datatables in InfyOm Laravel GeneratorLaravel

How to use Datatables in InfyOm Laravel GeneratorLaravel
InfyOm Laravel Generator comes with two possible choices for a table in the index view.
- Native table with blade
- Datatables
Datatables comes with a huge set of features if you really need it and InfyOm Generator is capable of generating your CRUD table with Datatables. It uses yajra/laravel-datatables-oracle for that. But I heard from lots of people that they got confused about the installation of that package and how to use it with Generator. so I decided to write a post on that.
Yajra datatables come with a few different packages, one for core datatables and other plugins like buttons, HTML, export CSV etc. When you are using it with InfyOm Generator, you will need all of them since we generate a table with a full set of features.
Perform the following steps.
Step 1: Add Packages
In the first step, we need to add these packages into our project based on the laravel version we are using. Check the following table:
Laravel Version | yajra/laravel-datatables-oracle | yajra/laravel-datatables-buttons | yajra/laravel-datatables-html |
---|---|---|---|
5.5 | 8.x | 4.x | 4.x |
5.6 | 8.x | 4.x | 4.x |
5.7 | 8.x | 4.x | 4.x |
5.8 | 9.x | 4.x | 4.x |
Based on your laravel version, install these packages and add the following service providers and facade in config/app.php.
/** Service Providers **/ Yajra\Datatables\DatatablesServiceProvider::class,
Yajra\Datatables\ButtonsServiceProvider::class,
Yajra\Datatables\HtmlServiceProvider::class,
/** Facade **/
'Datatables' => Yajra\Datatables\Facades\Datatables::class,
Step 2: Run Vendor Publish
Once you add this, publish the assets for all these service providers. This is also one critical step. Make sure you run a vendor:publish for all these service providers. Or you can just run php artisan vendor:publish and select the service provider from the list and do this for all of these three service providers. It will publish some assets into your public directory.
Step 3: Enable Datatable option for Generator
After publishing assets, go to config/infyom/laravel_generator.php and make add_on => datatables => true.
Step 4: Scripts and CSS section into blade layout (Optional)
If you have used publish layout option then you can skip this step. Otherwise, make sure you have scripts and CSS sections into your main blade layout file. Since that's where all scripts and CSS will be added for datatables.
And that's it. Try to generate CRUD for some model and it should generate your crud with Datatables.
Introducing Laravel 5.8 support to InfyOm Laravel GeneratorLaravel

Introducing Laravel 5.8 support to InfyOm Laravel GeneratorLaravel
Introducing Laravel 5.8 support to InfyOm Laravel Generator with more cleaner Repository Pattern
Laravel 5.8 just released this week with a bunch of new improvements. You can read the full post here about new updates. so in a very small fraction of time, we also worked on adding support for Laravel 5.8 into our generator. You can read the installation steps here.
Also, one another feature or improvement we have done is, we tried to create a cleaner and extendable repository pattern while generating CRUD. so far we were using prettus/l5-repository package, which is really awesome if you do not want to write your general functions of create/all/update/delete/find in all of your repositories. I really loved that package and that's the reason we extended that package when we created our repository.
This is all great when you are talking about simple CRUD functions. But things get confusing when people want to customize their code. I got a lot of emails and also lots of people created issues on Github regarding how to customize that function based on their certain needs.
So with this version, I decided to write our own simple BaseRepository which will be published into app/Repositories/BaseRepository.php. so developers are free to customize all the basic functions.
Actually, this is also possible with prettus/l5-repository as well and with our generator as well by publishing templates. But that needs some more work and some deep knowledge of customizing templates. But with this update, it will be easier.
Right now, I do not expect any breaking changes who are migrating their code from 5.7 to 5.8 which is using a generator. I tried to keep all old BaseRepository classes and repository packages into dependencies. All their existing generated repositories should work fine.
Still, if someone is getting any errors then they can contact me by creating issues on Github. I will try to respond there.
Hope this release will help and people can start to get started to upgrade their code to Laravel 5.8.
Multi Column Search box in Datatables with InfyOm Laravel GeneratorLaravel

Multi Column Search box in Datatables with InfyOm Laravel GeneratorLaravel
UX and UI designs are similar and are often used interchangeably. In fact, these two words have completely different meanings and relay different activities. These two businesses have essentially been around for years, but only recently have been involved in the technology industry, which has been renamed to encourage UI and UX designers.
These two components are essential when it comes to digital products, but the roles are very different. They refer to various aspects of both product development as well as the actual design process. Although UX means "user experience" and UI means "user interface", both jobs cover much more than they seem, which makes learning UX and UI more important at the same time.
User Experience Design (UX)
Originally defined by a cognitive scientist named Don Norman, the term "user experience" was defined before the 21st century. He described UX as "all aspects of the end-user interaction with the company, its services, and its products".
UX can be applied to anything in life that creates an experience. Whether it's a website, a mobile app, a theme park, or a tea party. UX doesn't have to be related to anything in the world of graphic design. User experience is the user's interactions and user "experience" with a product or service.
When it comes to digital products or services, UX is concerned with how a web page, mobile application, or software perceives the user. This may include simplifying the website checkout process or simplifying the application for general use.
You could say that a UX design job requires marketing, design, and project management skills. It is a complex role. Regardless of whether it is being applied to a car, shoe, or website, UX Designer's main goal is to create a simple and pleasant user experience. The product needs to communicate the owner’s goals, while also meeting the needs of the user.
User Interface Design (UI)
UX and user interface (UI) are often compared or grouped in the same job description. These two modes are very different, leaving the UI to be misinterpreted.
Often when looking at job descriptions for UI offerings, you will see a closer description of graphic design. Although UI positions sometimes deal with parts of branding or even frontend development, they do not indicate the original position.
User interface design is a digital term. This is mainly where it differs from UX. A UI is simply an interaction between a user and a digital product or service. This may include a touchpad that allows you to select your coffee from an automatic coffee machine or from your computer screen. It also deals with applications and websites that look and feel how the user interacts with the product.
The main purpose of the UI is that the designer will use design tools that enable better communication between the designer and the developer. This in turn will facilitate implementation with developers.
The user interface is an incredibly important element that allows the user to trust the brand. The UI designer is also responsible for relaying the message of the product as well as its research and content into a compelling display or experience.
UX vs. UI
The comparison of UX and UI is almost like apple and orange. If you take the human brain with the right hand representing creativity (usually left-handed individuals), this would be the UI design. If the left side of the brain represents the analysis (usually right-handed individuals), then the left side UX.
UI design is creative, fuzzy, beautiful, and presentable. UX design is, alternatively, the optimization, organization, and structure of the data to be implemented. Without one or the other, the project cannot be completed. To complete the product, you may not lack UX or UI. Despite this, they have completely different roles with different functions.
In general, a UX designer will need to fully map the entire user's journey to solve a specific problem in a product. Much of the UX Designer's job is to understand the user's problems and how to solve them. UX designers work by researching to understand the users they are targeting and what their needs will be.
Alternatively, UI designers consider all aspects of the visual elements. Everything from the first screen to the last screen. The UI designer will make sure the colors are readable. This may include ensuring that a partially blind 65-year-old feels comfortable using the same screen as a normal 13-year-old.