Laravel introduction to Service Container — Part 1
We have to talk about the Service Container because it’s a powerful tool for managing class dependencies and performing dependency injection.
Dependency Injection: The classes we depend on are “injected ”via the constructor or other setter methods in our class
use App\Models\User;class UserController extends Controller
protected UserRepository $users;
public function __construct(UserRepository $users)
$this->users = $users;
public function get(int $id)
$user = $this->users->find($id);
In this example we have to retrieve some data from a database, so we need a repository ( where we most likely have DB queries to get our data ), and because the repository is injected it’s really easy to swap it out with another implementation and mock it for unit tests!
The Zero Configuration Resolution
It is a really simple concept yet it may be hard to grasp.
It states that if a class only depends on concrete classes, the container does not need to be instructed on how to resolve that class.
This means that those classes will be automatically resolved.
Thankfully, most of the things we do will receive their dependencies via the container. This will resolve all our dispatchers, listeners, middleware, etc.
Dependency Injection inside Laravel Jobs
Dependency injection should be made inside the handle method, not in the constructor as I have stated above.
class ProcessPodcast implements ShouldQueue
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct()
public function handle(PinService $pinService)