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 do you run a PHP script from the command line?

How to use Anonymous classes in PHP 7?

Is multiple inheritance supported in PHP?

What is snake case?

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to check if two strings are anagrams in PHP?

A list of operators on Eloquent's where() method

What is Bubble sort, and how to write an implementation of it in PHP

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to use subdomains as parameters in your routes (or in your web.php file)