lorisleiva / laravel-actions

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

add a controller that allows using any action as a route, without the need to explicitly define it in the routes #240

Open tommica opened 1 year ago

tommica commented 1 year ago

It feels a bit archaic to have to define routes for the actions, so rather than having to do that explicitly for each route, there is now a generic route for it: /laravel-actions/{actionString} - the idea is this:

I have a simple form that saves the blog post, and instead of using "route(...)" helper, we use the new "action_route(...)" helper like this:

<form action="{{action_route(\App\Actions\TestSubmit::class)}}" method="POST">
    @csrf
    <input type="text" name="text" />
    <input type="submit" value="SEND" />
</form>

When the route gets generated, the name of the action will be encrypted, to avoid any kind of shenanigans in regards of people trying to invoke any other action that they should not, f.x "MarkAsAdmin".

Under the hood this request will be handled by ActionController with this Route::any('laravel-actions/{actionString}', \Lorisleiva\Actions\ActionController::class)->name('laravel-actions.route'); definition, which will decrypt the action name and will call the defined action and return the result for it.

You can also generate the route to use some explicit functions if you want by doing something like this:

action_route(App\Actions\FooBar::class.'@myExplicitMethod');
action_route([App\Actions\FooBar::class, 'myExplicitMethod']);

You can also use it in a link:

<a href="{{action_route(\App\Actions\TestSubmit::class, ['text' => 'as a link'])}}">Link test</a>
edalzell commented 8 months ago

I really like this, but would also like the ability to set the route. The routes can be auto registered when the actions are registered. What do you think?

tommica commented 8 months ago

@edalzell Yeah, that could be neat - do you have any time to add that to the codebase?

edalzell commented 8 months ago

@edalzell Yeah, that could be neat - do you have any time to add that to the codebase?

Not right now I don't, sorry. Trying to get a new SaaS app out the door.

edalzell commented 6 months ago

More ideas, like Livewire/Spatie Data, we could use PHP attributes perhaps for this, or separate properties.