Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

22 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()]);
    }
}

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More