Posts Learn Components Snippets Categories Tags Tools About
/

How to create Laravel Invokable Controller in Laravel

Learn how to generate Laravel invokable controller and dedicate the class for the particular action

Created on Jul 02, 2021

357 views

Sometimes you can have an action in a controller that's performing some specific large action. To dedicate the entire controller to that dedicated action you can create an invokable controller.

Using the command line, you can write the normal command to create the controller but make sure to add the "--invokable" flag.
php artisan make:controller ShowPost --invokable

The generated controller will be as follows.
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class ShowPost extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        return view('posts.show', ['post' => Post::first()]);
    }
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)