DEV Community

Cover image for Laravel Invokable Controller
Ahmet Korkmaz
Ahmet Korkmaz

Posted on

Laravel Invokable Controller

Hello to everyone! In this article, we will examine how the __invoke method is used in the Laravel controller.

First of all, let's see what the __invoke method in php does:
The __invoke method is called Magic Method. Used to make a class run as a function.

To use this in Laravel, it is necessary to use --invokable as a parameter when creating the controller with the help of artisan.

php artisan make:controller UploadController --invokable
Enter fullscreen mode Exit fullscreen mode

After running the bash command above, a controller class will be created as follows:


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UploadController extends Controller
     * @return \Illuminate\Http\Response
    public function __invoke()
        // ...
Enter fullscreen mode Exit fullscreen mode

After doing the work you want to do for the application in the __invoke method in the controller, we need to define the controller in routes. To define the API, it can be added as follows.

// routes/api.php

Route::post('upload', UploadController::class);
Enter fullscreen mode Exit fullscreen mode

As a result, you can use an invokable controller when you only want to use a single method in a controller class and you don't need basic methods (index, store, update etc.) in the controller.

Happy coding! 🥳

Top comments (0)