Service Provider in Laravel

#code-section {
  font-family: 'Courier New', Courier, monospace;
  font-size: 16px;
  border: 1px solid #ccc;
  padding: 10px;
  background-color: #f8f8f8;
  color: #333;
}
#code-section pre {
  white-space: pre-wrap;
}

In last guide we learned about Service Container in Laravel and i told you about that we will make a new guide about Service Provider in Laravel.

In Older version of laravel there was no Service Provider and people was keep asking where we should put the service to the service container and where should we bind them. Then Laravel launch this feature to clear all confusion.

Service Provider in Laravel

Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services, are bootstrapped via service providers.

By Laravel

As per Laravel its a center point where all laravel and your own services Power Ups. did i said Power Up? Yes because its automatic process to register service container bindings, events listeners, middleware and routes etc.

Let’s take a look at config/app.php file there is a providers array which have all service provider classes that will load for your laravel application.

A fresh laravel app has a set of Laravel core service provider that is listed in providers array.

These are Laravel Components such as Mailer, Cookies, Cache, Database, Session and many more.

Some Provider are deferred provider that not load on every request and load only when needed.

Why We Need a Service Provider?

As we see in last guide of Service Container there we use a Service successfully without any service provider so why we need this one. The Answer is very simple when we have one or more required parameter and dependency in our service then we need to provide the dependency to that particular service we need to instantiate into the service class so that time we need a service provider.

Creating a Service Provider

Service Provider is a Class that extends Illuminate\Support\ServiceProvider class. A service provider contain at least two method when we make by artisan command one is register() and second is boot().

Artisan Command to Make a Service Provider

PowerShell$ php artisan make:provider MyTestServiceProvider

After run this command you will get a new provider in your app/Providers folder of your Laravel App.

PHP namespace App\Providers; use Illuminate\Support\ServiceProvider; class MyTestServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { // } /** * Bootstrap services. * * @return void */ public function boot() { // } } $.ajax({ type: 'GET', url: routeUrl, success: function(data) { // Handle the response data here }, error: function() { // Handle errors here } });
Leave A Comment