How do Invokable Controllers work in Laravel?

Laravel: How do Invokable Controllers work in Laravel?

If a controller in Laravel has just one action then you simplify the controller by using the __invoke() method. Create a controller with a __invoke() method, then in your routes files you can just do the following:

  1. Route::get('home','HomeController');

The controller code for HomeController could look something like this:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. class HomeController extends Controller
  5. {
  6.     public function __invoke(Request $request)
  7.     {
  8.         return "Welcome to our homepage"
  9.     }
  10. }

Create the controller using this artisan command:

php artisan make:controller HomeController --invokable

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How do Invokable Controllers work in Laravel?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to check if a relation was loaded on an Eloquent model already?

How to exclude URLs from the Laravel CSRF protection?

What are macros in Laravel?

Force trailing slash (redirect if no trailing slash exists) in .htaccess

How to set environmental variables in your .htaccess file

How could you include a custom function for every single time PHP runs?

What are the main error types in PHP

When is __destruct called in PHP?

How to get the last character of a string in JS?

How to disable file hotlinking in Apache with .htaccess