Skip to content

v1.1.0

Compare
Choose a tag to compare
@lorisleiva lorisleiva released this 23 May 12:43

This release slightly adjusts the dependency injection logic by supporting nullable typehints. Let's go through a few examples to understand what that really means.

A) Optional injections

Assuming $service is not an attribute of this action, prior to this version, it would have resolved the MyInjectedService class from the container even though it's an optional typehint (notice the ? prefix). Now, it will not even try to resolve it from the container. This mechanism can be helpful to turn dependency injection off for certain arguments.

class MyAction extends Action
{
    public function handle(?MyInjectedService $service)
    {
        // ...
    }
};

The reason behind this change is to make sure Laravel Actions does not try to become too intrusive when resolving the arguments of your methods.

B) Optional route bindings

Consider the example below where the User model is typehinted but marked as nullable. Prior to this version, Laravel Actions would have thrown an exception if the provided user identifier did not successfully retrieve a user from the database. Now, it will return null instead of throwing an exception if the user cannot be found via the provided identifier.

class MyAction extends Action
{
    public function handle(?User $user)
    {
        // if $user is "1" and User::find(1) exists, it returns the fetched model.
        // if $user is "42" and User::find(42) does not exist, it returns null instead of throwing an exception
        // if $user is null, it returns null instead of throwing an exception
    }
};

The reason behind this change is to allow a more flexible route model binding.


Whilst these changes can break some existing code (hence the jump to 1.1) it is very unlikely that it will. Chances are, if you were marking a typehint as nullable before, you were already planning for that argument to be null.