Instance not created Spatie Role and Permission

431 views Asked by At

I made a provider and link the repository, but I get the error:

exception: "Illuminate\Contracts\Container\BindingResolutionException" file: "../vendor/laravel/framework/src/Illuminate/Container/Container.php" line: 1038 message: "Target [Illuminate\Database\Eloquent\Model] is not instantiable while building [App\Http\Controllers\Api\V1\User\RoleController, App\Repositories\Model\RoleRepository]." trace: [,…]

Namespaces:Spatie\Permission\Models\Role; and Spatie\Permission\Models\Permission;

RepositoryServiceProvider:

class RepositoryServiceProvider extends ServiceProvider
  {
    // ...
    $this->app->bind(ModelRepositoryInterface::class, function() {
      return new PermissionRepository(new Permission);
    });
    
    // ...
  }

During debugging, installed dd(new Role). And got this error:

"Call to a member function connection() on null"

What is the problem?

1

There are 1 answers

0
doox911 On

Since I use the same interface, but different classes (controllers) they need to be bound like this:

$this->app->when(RoleController::class)
  ->needs(ModelRepositoryInterface::class)
  ->give(function () {
    return new RoleRepository(new Role);
  });

$this->app->when(PermissionController::class)
  ->needs(ModelRepositoryInterface::class)
  ->give(function () {
    return new PermissionRepository(new Permission);
  });

See documentation.