Skip to content

[11.x] Add Request::fluent method#53662

Merged
taylorotwell merged 4 commits into
laravel:11.xfrom
stevebauman:request-fluent
Nov 25, 2024
Merged

[11.x] Add Request::fluent method#53662
taylorotwell merged 4 commits into
laravel:11.xfrom
stevebauman:request-fluent

Conversation

@stevebauman

@stevebauman stevebauman commented Nov 25, 2024

Copy link
Copy Markdown
Contributor

Description

This PR adds a new fluent() method to the Illuminate\Http\Request class.

Similar to the Request::collect method, being able to transform the request input to a Fluent instance helps in being able to transport the input data around your application (such as an action or a queued job) and provides you null-safe access instead of using an array.

Usage

Consider an action that consumes a Fluent instance to access request data safely that may be nullable, while also being portable for easy testing without having to provide a request instance:

use App\Actions\CreateComment;

class CommentController extends Controller
{
    public function store(CommentRequest $request)
    {
        $comment = (new CreateComment)->handle(
            $request->fluent()
        );

        return response($comment);
    }
}

class StoreComment extends QueuedJob
{
    public function __construct(
        public Fluent $data
    ) {}

    public function handle(): Comment
    {
        return Comment::create([
            'title' => $this->data->title,
            'body' => $this->data->body,
            // ...
        ]);
    }
}

@taylorotwell
taylorotwell merged commit 018d778 into laravel:11.x Nov 25, 2024
@GavG

GavG commented Nov 28, 2024

Copy link
Copy Markdown

Nice 👌 what're your thoughts on a FluentRequest class that can be used to type hint the controller function param to allow auto-injection of the fluent wrapped version, avoiding need for the manual call to ->fluent()?

Easy enough to write in userland I guess, but a nicety I'd probably never get round to in my projects.

@stevebauman

Copy link
Copy Markdown
Contributor Author

@GavG I'm not sure if that'd be easily do-able, and/or worth the pay-off, imo. How would it work?

@GavG

GavG commented Nov 29, 2024

Copy link
Copy Markdown

@GavG I'm not sure if that'd be easily do-able, and/or worth the pay-off, imo. How would it work?

Having had a look through, I'd agree, it's not worth the pay off.

It could be done when resolving controller method params, but it wouldn't be especially clean. Users who wanted to could, I think, use a custom contextual cast.

So I retract my idea, for the sake of saving one line of code 😂

@stevebauman

Copy link
Copy Markdown
Contributor Author

@GavG haha okay sounds good! Appreciate the discussion though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants