Invokable Controllers with One Specific Action

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses