Home / Snippets / How to create Laravel Invokable Controller in Laravel
How to create Laravel Invokable Controller in Laravel cover

How to create Laravel Invokable Controller in Laravel

392

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this