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

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

How to enable the rewrite engine in .htaccess?

How to hide directory listing in .htaccess?

How to Enable Directory Listings in Apache with .htaccess

How to block multiple IP addresses in .htaccess

Remove trailing slash (redirect to remove trailing slash) in .htaccess

What are the SPL data structures

How to find out which php.ini file PHP is using?

How to hide certain file types from directory listings

How to convert between types in JS?