-1

In my Laravel 6.9.0 app, I have some code which I need to run from many places, so I'm working on creating this as a service layer.

I've created the file /app/Actions/Music/GetRecentArtists.php and added it to my composer autoload config:

<?php

namespace App\Actions\Music;

use \Barryvanveen\Lastfm\Lastfm;

class GetRecentArtists {

    public function get(Lastfm $lastfm)
    {
        return true;
    }

}

But when I run it in Tinker using:

(new App\Actions\Music\GetRecentArtists())->get()

I get the following error:

TypeError: Too few arguments to function App/Actions/Music/GetRecentArtists::get(), 0 passed in Psy Shell code on line 1 and exactly 1 expected

I'd thought that dependency injection would inject the Lastfm instance. When I remove the function argument, it runs fine.

Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • Not really related to dependency injection, but might be better to use a [scope](https://laravel.com/docs/6.x/eloquent#local-scopes) instead. – Adam Rodriguez Jan 14 '20 at 23:16
  • where is located Barryvanveen\Lastfm\Lastfm class? best approach load in composer file and run dumpautoload command – sajjad Jan 15 '20 at 01:19
  • 1
    Laravel dependency injection only works if you pull the `GetRecentArtists` from the service container. It does not work if you create it yourself. – PtrTon Jan 15 '20 at 18:37

1 Answers1

0

If you use the resolve method, the Laravel service container should inject the dependency for you:

resolve('App\Actions\Music\GetRecentArtists')
D Malan
  • 10,272
  • 3
  • 25
  • 50