DEV Community

Discussion on: Creating your first API with Laravel in the proper way

Collapse
 
martinbean profile image
Martin Bean

You can use Auth() class here to get current user and check permissions if needed.

You can also just use $this->user() since you’re in a form request and it extends Laravel’s Request class.

You can also drop the authorize method if all you do is return true. Form requests will only invoke it if it exists; otherwise it’ll just let the request through.

Your “user store service” is also more like a command or “action” rather than a user service class. If you resolve it from the container, you should inject the hasher instance instead of relying on a facade again so you can easily test it without the framework needing to be booted:

use Illuminate\Contracts\Hashing\Hasher;

class UserStoreService
{
    protected $hasher;

    public function __construct(Hasher $hasher)
    {
        $this->hasher = $hasher;
    }

    public function __invoke(string $email, string $name, string $password): User
    {
        $password = $this->hasher->make($password);

        return User::create([
            'email' => $email,
            'name' => $name,
            'password' => $password
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode
public function testItCanCreateUsers(): void
{
    $hasher = Mockery::mock(Hasher::class);

    $service = new StoreUserService($hasher);

    // Now test service class
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
victoor profile image
Víctor Falcón

Good points! Usually I like to use facades because they are really easy to test with Laravel and it's something common, but it's true that you need to load the framework for that. 😉