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

301 Redirect a single URL in .htaccess to a new location

How to order a Laravel hasMany relationship?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to force non www in htaccess

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

How to merge/concat two arrays together in JS?

How to undelete a soft deleted Eloquent row?

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

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to remove .php from the end of URLs with .htaccess