- Messages
- 27
- Likes
- 6
- Trophy Points
- 5
- Followers
- 2
- Joined
- Mar 17, 2022
Definition
Invokable Controller is a controller that contains only one (__invoke()
) method.The
__invoke(
) method is a magic method that is called when a script tries to call an object/class as a function.Invokable controllers come in handy when you need to create a controller that does one thing and you are struggling with that one method name.
Although it may be better to consider using one of the seven CRUD actions (index, create, store, show, edit, update, destroy).
How to create an invokable controller in Laravel
To create an invokable controller, run the following command:
Bash:
php artisan make:controller HomepageController --invokable
As you can see, the command is almost the same as when you are trying to create a regular controller, except for the
--invokable
flag.After running the artisan command above, a controller class will be created as follows:
PHP:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class HomepageController extends Controller
{
/**
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
// ...
}
}
To call this controller, we need to define a new route:
PHP:
// routes/web.php
Route::get('/', HomepageController::class);
Passing parameters to Invokable Controllers
You can also pass parameters when using invokable controllers in the same way as you do with regular controllers.
PHP:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
*
* @return \Illuminate\Http\Response
*/
public function __invoke($user)
{
// ...
}
}
PHP:
// routes/web.php
Route::get('/users/{user}', UserController::class);