wturrell's avatar

Correct Artisan make:controller syntax for Action controllers

I'd like an invokable controller, but without the Request $request in the __invoke method. Is there a way to do that with Artisan? (Or is there a good reason not to do it?)

It's for what I'd call Business Logic, which I may need to use in more than once, and is to go in App/Actions.

0 likes
5 replies
LaryAI's avatar
Level 58

Yes, you can create an invokable controller without the $request parameter by using the __invoke method in the controller class. Here's an example of how to create an invokable controller using Artisan:

php artisan make:controller Actions/MyAction --invokable

This will create a new invokable controller in the App/Http/Controllers/Actions directory. You can then remove the $request parameter from the __invoke method in the controller class:

namespace App\Http\Controllers\Actions;

class MyAction
{
    public function __invoke()
    {
        // Your business logic here
    }
}

You can then use this controller in your routes like this:

Route::get('/my-action', 'Actions\MyAction');

Note that if you need to pass parameters to your controller, you can do so by adding them to the __invoke method:

namespace App\Http\Controllers\Actions;

class MyAction
{
    public function __invoke($param1, $param2)
    {
        // Your business logic here
    }
}

And then passing them in your route:

Route::get('/my-action/{param1}/{param2}', 'Actions\MyAction');
wturrell's avatar

@LaryAI sorry Lary, but this is another case of you confidently telling me something which simply doesn't work. So far you have never given me an answer that is even close to 100% correct, all you do is repeat my question back to me and suggest something that doesn't work.

The --invokable switch doesn't remove the Request parameter. You also omitted the App/ from the beginning of the namespace, which means Laravel creates it under /app/Http/Controllers.

Snapey's avatar
Snapey
Best Answer
Level 122

controllers are for handling http requests

Anything else is just a class in the right folder.

Why do you need an artisan command for this?

Snapey's avatar

here's a template you can cut and paste

<?php

namespace App\Actions;

class {YourClassname}
{
    public function __invoke()
	{

	}

}
1 like

Please or to participate in this conversation.