Skip to content
Advertisement

How to use an Interface Repository in a Laravel Nova Action?

I’m using the Laravel Repository Pattern to manage my resources and I was wondering how can I use an interface inside a Nova Action? Since an Interface cannot be instanciated, I was wondering how I could use my Interfaces within my action?

In my Controller constructor I create my repository and then I’m able to use it within my functions, but I can’t figure out how to do the same thing inside a Laravel Action.

Any idea how I could do this?

An example in my Controller

private $myRepository;

public function __construct(
    MyRepositoryInterface $myRepository,
)
{
    $this->myRepository = $myRepository;
}

And then inside a function I can do something like

public function destroy($id)
{
    $this->myRepository->delete($id);

    return response()->json( array("message" => "success") );
}

Now in my Nova Action, here’s what I’m trying to do

public function handle(ActionFields $fields, Collection $models)
{
    foreach ($models as $model)
    {
        $myRepository = new MyRepositoryInterface(); // This doesn't work obviously
        $myRepository->customManipulation($model->id);
        $this->markAsFinished($model);
    }
}

Any idea how I could use my repositories?

Thanks!

Advertisement

Answer

You can do $myRepository = App::make(MyRepositoryInterface::class);, IoC will resolve it and will instantiate a class instance.

I assume you have already bound the class to the interface:

App::bind('MyRepositoryInterface', 'MyRepository');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement