Laravel's post

The OneSingnal is the market leader in push notification providers. It provides the mobile + web push, email & in-app messages and easy way to send notifications. OneSignal provides an officially core PHP APIs but not 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..

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,

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_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.

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

Checkout 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

Recently, the Laravel team announced a Laravel Fortify. A framework agnostic authentication backend for laravel applications. It provides registration, authentication along with two-factor authentication.

As said above, it is a framework agnostic, so it doesn't provide any blade views with it. You can implement views of your choice of the frontend. Blade, Vue, React with Bootstrap or TailwindCSS, or any other CSS framework.

Today we are going to see how we can use Laravel Fortify with one of the most popular Bootstrap 4 theme AdminLTE v3.

We can actually do that in minutes with the package that we already developed called Laravel UI AdminLTE.

This package also works with the previous laravel version to have an authentication system with Laravel UI for Laravel Frontend Scaffolding.

Let's see step by step, how we can do that.

Install Packages

Install Laravel Fortify and Laravel UI AdminLTE by the following command,

composer require laravel/fortify infyomlabs/laravel-ui-adminlte

Publish Fortify Resources

This command will publish all required actions in the app/Actions directory along with the Fortify configuration file and migration for two-factor authentication.

php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"

Run Migrations

Then run migrations,

php artisan migrate

Add Fortify Service Provider

Next step, add published FortifyServiceProvider to config/app.php

Run AdminLTE Fortify Command

Run the following command,

php artisan ui adminlte-fortify --auth

Install Node Modules and Run a Build

As a next step, install required npm modules and run a build,

npm install && npm run dev

And we are done. Now visit the home page and you should be able to see the full authentication system working including,

  • Login
  • Registration
  • Forgot Password
  • Reset Password
  • Home page

Laravel AdminLTE UI also provides a starting layout with a sidebar menu and header once you do login. so you are all set to go.

June 27, 20202 minutesauthorMitul Golakiya

Sometimes we need to load a large amount of data into memory. Like all the models we have in the database.

For e.g. PDF Printing, Perform some global updates, etc.

So the general practices we use in Laravel is to write the following code,

$users = User::all();

Just imagine I have 10,000 users in the database and when I load all the users in one shot.

But it takes a really high amount of memory to load all the records and prepare Laravel Model class objects. And sometimes we also load them in chunks to save the memory, but in some use cases, chunking can not be the option.

Here is the screenshot of mine when I load 10,000 users into memory with the above code.

10k Models

It's using 37MB memory. Also, imagine the required memory if we are loading some relationships as well with these 10,000 records.

The Eloquent model is a great way to handle operations with lots of features like Mutators, Relationships, and much more.

But we really do not use these features all the time. We simply output or use the direct values which are stored in the table. So ideally, we do not need an eloquent model at all, if we are not going to use these features.

In those cases, Laravel also has a handy function toBase(). By calling this function it will retrieve the data from the database but it will not prepare the Eloquent models, but will just give us raw data and help us to save a ton of memory.

So my revised code will look something like this,

$users = User::toBase()->get();

Check the revised memory screenshot after adding the toBase function.

10k Models toBase

So it almost saves 50% of the memory. It's reduced from 35MB to 20MB and the application also works much much faster, because it doesn't need to spend time in preparing 10,000 Eloquent models.

So if you are not really going to use features of Eloquent and loading a large amount of data, then the toBase function can be really useful.

Here you can find a full video tutorial for the same.

June 21, 20202 minutesauthorMitul Golakiya

Recently, I've started working on one project where we follow modules pattern and for the same, we have different assets folder for the different modules and the folder named common for assets which are common across all the modules.

So our public folder looks like the following,

Module Asset Functions

The problem that I started facing was everywhere I need to give a full path to import/include any of the files from any of the folders. For e.g.

<img src="{{ asset('assets/tasks/images/delete.png') }}" alt="Delete Task">

Even if we have some folder in images to group similar images then it was even becoming longer. For e.g.

<img src="{{ asset('assets/tasks/images/social/facebook.png') }}" alt="Facebook">

The workaround that I used is, I created one file called helpers.php and created dedicated asset functions for each of the modules. For e.g., for tasks,

if (!function_exists('tasks_asset')) {
     * Generate an asset path for tasks module folder.
     * @param  string  $path
     * @param  bool|null  $secure
     * @return string
    function tasks_asset($path, $secure = null)
        $path = "assets/tasks/".$path;
        return app('url')->asset($path, $secure);

With this function, I can use,

<img src="{{ tasks_asset('images/delete.png') }}" alt="Delete Task">

Other advantages it gives are,

  1. if in future if the path of tasks folder changed, then I do not need to go and update every single import/include.
  2. I (or any new developer) do not need to remember the long paths and can always use direct function names for modules.

Even I like this pattern so much, so I went further and created dedicated image function as well,

if (!function_exists('tasks_image')) {
     * Generate an asset path for tasks module images folder.
     * @param  string  $path
     * @param  bool|null  $secure
     * @return string
    function tasks_image($path, $secure = null)
        $path = "images/".$path;
        return tasks_asset($path, $secure);

So I can use it as,

<img src="{{ tasks_image('delete.png') }}" alt="Delete Task">

Simple and handy functions to use everywhere.

May 16, 20202 minutesauthorMitul Golakiya

Last month, I got consulting of one Laravel project where we have to perform some complex validations.

The scenario was while creating an order, either customer can select the existing address from the dropdown or he may have an option to create a new address with all address fields.

And when a customer hits enter, the backend needs to validate, if address_id is sent into request then it needs to check if that address id exists and then use that address_id for that particular order. Otherwise, it needs to check if required fields (address1, city, zip, country) for address are sent then use them, create a new address and use that new address_id.

so far how validation was happening was manual, so in controller this all manual validation was happening. But I don't find that a proper way. The goal was to do validation from CreateOrderRequest only. so it goes back with proper laravel error messages from a request only and displays them on the page. so we actually do not need to make any manual efforts to make this happen.

That's where required_without validation rule helped us.

The UI was something like this,


In the above UI, customers can either type Address1, Address2, City and Zip or just go and select an existing address from the dropdown.

To do this validation from form request, we used the required_without rule as following, 'address_id' => 'required_without:address_1,city,zip|sometimes|nullable|exists:addresses,id',

Now let's try to understand what's happening here. To understand it better let's divide the rules

  1. required_without:address_1,city,zip
  2. sometimes
  3. nullable
  4. exist:addresses,id

1. required_without:address _1,city,zip

This rule validates that address_id field is required without the presence of address_1, city and zip fields

2. sometimes

This means, address_id fields will be passed only sometimes and not required all the time. We need this because when address_1, city and zip fields will be present then we do not need it at all.

3. nullable

This means, address_id fields can be null since it will be null when a customer does not select the address from the dropdown.

4. exist:addresses,id

The passed value in address_id fields, must exist in the addresses table.

So this is how we solved this complex validation in a very easy way by using multiple powerful laravel validation rules.

Hope this can help others as well.

January 07, 20202 minutesauthorMitul Golakiya

Last week, we were working on one project where we were using LaravelCollective for generating our form. LaravelCollective is a really awesome package and reduces lots of efforts, specifically for automatically binding old inputs to our forms.


With LaravelColletive when we pass null as a second value, it tried to get old inputs if available and inject them. But for some reason, it was not working with datetimelocal.

datetimelocal need a date in Y-m-d\TH:i Format. When I went into the code of FormBuilder.php, it’s already managing that and tries to convert date into that format if you have passed DateTime object.

So it was completely working fine while creating a record when you do not have any value.

But I have the same form which was used at both the time of Create and Update. And I was passing null into value field at both of the time and LaravelCollective injects it automatically from model or old inputs if there is some error. Something like following,

<div class="form-group col-sm-6">
    {!! Form::label('due_date', 'Due Date:') !!}
    {!! Form::datetimeLocal('due_date', null, ['class' => 'form-control']) !!}

So, Due date will be automatically placed from the model. It’s working fine with all other fields except datetimelocal.


The reason behind that is, the value is retrieved from model due_date field, but it comes in Carbon instance and when it converts to a date string, it’s converted into default format which is Y-m-d h:i:s. So it will not work for datetimelocal input since it requires Y-m-d\TH:i format.

So as a solution, what change we did is, instead of passing null value, we first check, if the model is there then pass the value directly to the input. Something like,

<div class="form-group col-sm-6">
    {!! Form::label('due_date', 'Due Date:') !!}
    {!! Form::datetimeLocal('due_date', (isset($task)) ? $task->due_date : null, ['class' => 'form-control']) !!}

So, I will check if I have passed the model $task to the view and then I will pass a due_date value to input. So FormBuilder will convert it to the proper format and it will get displayed into an input.

Now, when we save the form, it will also return date into Y-m-d\TH:i format, so again we need to convert it to the proper format. For that, we created a mutate attribute for due_date in my Task Model.

public function setDueDateAttribute($value)
   $this->attributes['due_date'] = Carbon::parse($value);

And that’s it. Our datetimelocal input gets working. I have seen lots of issues on stackoverflow for it. So hope it may help someone.

November 14, 20192 minutesauthorMitul Golakiya

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 change it from the environment directly.

Use Case

Imagine you have two SMS Providers called ABC and XYZ that you are using into 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 other SMS service provider. Just like when you change any driver in Laravel App like Log, Cache, Queue, Database, etc.

so let's figure out, how to do that.


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,


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 given the same parameters.

Create SMS Service Implementations

The second step is to create the real implementation of our SMS Services which will be responsible to send 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,


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,


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,


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 accessor. 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,


return [
    'sms' => env('SMS_SERVICE')

Define your driver in .env file

Update your .env file and add SMS_SERVICE variable, something like


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.


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.

November 08, 20193 minutesauthorMitul Golakiya

We are working on an inventory system for one of our client 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:

Here are the installation steps and how to use this package.


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,



For UPC Lookup, use the lookup method by calling,



For Search API, you can use the search method,

\UPCItemDB::search('iphone 6');

\UPCItemDB::search('iphone 6', [
    'brand' => 'apple'
November 05, 20191 minuteauthorMitul Golakiya