lorisleiva / laravel-actions

⚡️ Laravel components that take care of one specific task
https://laravelactions.com
MIT License
2.52k stars 124 forks source link

Controller Actions not being authorized and validated #115

Closed tklie closed 3 years ago

tklie commented 3 years ago

Hi, first off: Thanks for the great package.

There seems to be an issue with authorization and validation in controller actions though. Assuming the following action:

class CreatePost
{
    use AsAction;
    use WithAttributes;

    public function rules(): array
    {
        return [
            'body' => ['required', 'string']
        ];
    }

    public function handle(string $body): Post
    {
        return Post::query()->create([
            'body' => $body,
        ]);
    }

    public function asController(ActionRequest $request): Post
    {
        $validated = $request->validated() // -> Exception

        // ... some other logic

        return $this->handle($validated['body']);
    }

    public function jsonResponse(Post $post): PostResource
    {
        return new PostResource($post);
    }
}

Authorization and validation are being skipped completely; also the call to $request->validated() within the asController method throws the following exception:

Call to a member function validated() on null

Apparently the ActionRequest's validator instance is null since the validate() method never gets called. Manually calling $request->validate() as the first line in asController solves this issue, but the documentation makes it seem like ActionRequests should be authorized and validated automatically. Did I misunderstand the documentation or has this method call been overlooked?

Thanks!

tklie commented 3 years ago

I just saw that the WithAttributes traits disables automatic validation - my mistake!