Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

realtebo's avatar

How to start creating service provider?

I started with

php artisan make:provider CartServiceProvider

Then I added to config\app.php, inside providers array this

App\Providers\CartServiceProvider::class,

This is the full actual code , comment striped out and compacted to a betetr reading, of the provider itself.

<?php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

class CartServiceProvider extends ServiceProvider
{
    public function boot()   {   }

    public function register()  {  }

    public function test()
    {
        return "Cart Service is working";
    }
}

I'm trying now to use it into one of my controller. I added

use App\Providers\CartServiceProvider;

Then into one of the controller action I tried to inject the provider

public function index(CartServiceProvider $cart)
{
    return view('customer_area.dashboard')
            ->with('cart', $cart);
}

I don't have modified yet the view.

Problem

When I access to index action of this controller, I got the exception

Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Support\ServiceProvider

This is now obscure for me how to fix this....

0 likes
3 replies
realtebo's avatar

@JackJones Thanks...

I've create App\Cart\Cart.php

<?php
namespace App\Cart;
class Cart {
    private $user;
    public function __construct(App\User $user)
    {
        $this->user = $user;
    }

    public function test()
    {
        dd($this->user);
    }
}

Then changed CartServiceProvider to register my class

use App\Cart\Cart;
..... 
public function register()
    {
        $this->app->singleton(Cart::class, function ($app, $user) {
            return new Cart($user);
        });
    }

But now ? How can Iinject my service provider?

realtebo's avatar

Works !

cart.php class

<?php

namespace App\Cart;

use App\User;

class Cart {

    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function test()
    {
        echo  $this->user->email;
    }
}
public function register()
    {
        $this->app->singleton(Cart::class, function ($app) {
            return new Cart(Auth::user());
        });
    }

in controller

use App\Cart\Cart;
...
public function index(Request $request, Cart $cart)

in view

{{ $cart->test() }}

Please or to participate in this conversation.