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 destroy or remove a cookie in PHP

How to show a specific view file for certain error codes?

How to select all rows for a certain month (or day, year or time), using Eloquent

How to hide directory listing in .htaccess?

How to make multiple routes share the same URL structure or URL parameters

How to install and use optipng on Linux CentOS

How to force gzip compression in Apache with .htaccess

How to check if two strings are anagrams in PHP?

How to pick what array_intersect function to use in PHP?

How to manually write your own pagination in PHP