Posts Learn Components Snippets Categories Tags Tools new About
/

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

Learn how to get or resolve a Class / Object / Contaract from the Service Container in Laravel the easy way

Created on Oct 22, 2021

41 views

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

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

)