Home / Snippets / How to Resolve Class or Contract from Service Container in Laravel 8
How to Resolve Class or Contract from  Service Container in Laravel 8 cover

How to Resolve Class or Contract from Service Container in Laravel 8

485

2 years ago

0 comments

To resolve classes, objects, or contracts from a service Container from Laravel you can make use of the "App" facade or "app()" helper method. Do refer to the code example below for the full example.

Using "App" Facade or "app()" Helper

use App\Services\Transistor;
use Illuminate\Support\Facades\App;

// Using the "App" facade
$transistor = App::make(Transistor::class);

// Using the "app" helper method
app(Transistor::class);

Calling from Service Provider


If you want to call it from the Service Provider then you can write your code like below. Do note that it's accessible from within the "$this->app" property.
$this->app // get Laravel underlying provider
Full code example on calling the provider from Service Provider Class.
<?php

namespace App\Providers;

use App\Services\Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection(config('riak'));
        });
    }
}

Other Reads

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this