Skip to main content
Tutorial Free

Invokable Controllers with One Specific Action

January 03, 2019
1 min read

Sometimes you need to create a controller which doesn't cover all seven resourceful methods, like index(), create(), store() etc. You just need controller which does one thing and you're struggling how to name that method. No more struggle, there's __invoke() method.

Since Laravel 5.6.28, you can create a Controller with only one method __invoke():

namespace App\Http\Controllers;

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

class ProfileController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function __invoke($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

As you can see, you can also pass a parameter to id.

To call that method+Controller, in your routes/web.php you should have this:

Route::get('user/{id}', 'ProfileController');

You can also generate this kind of Controller, with this Artisan command:

php artisan make:controller ProfileController --invokable

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

[NEW] Building a Typical Laravel SaaS

11 lessons
1 h 36 min

Laravel Modules and DDD

16 lessons
1 h 59 min

Claude Code for Laravel Projects: Crash Course

8 lessons
48 min

Comments & Discussion

A
alin ✓ Link copied!

Exceptionally succint and useful!

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.