Single Action Controller in Laravel

Laravel-Nepal
Apr 3 · 2 min read

Introduction

Before going to the topic , we will learn little about the __invoke() method. __invoke method is an amazingly useful PHP magic method. This feature is available since PHP 5.3.0 . This method allows us to treat our object as a function or a closure.

# Example

<?php/**
* Class Addition
*/
class Addition
{
/**
* The first integer value
*
* @var $numA
*/
public $numA;
/**
* The second integer value
*
* @var $numB
*/
public $numB;
/**
* Addition constructor.
*
* @param $numA
* @param $numB
*/
public function __construct($numA, $numB)
{
$this->numA = $numA;
$this->numB = $numB;
}
public function __invoke()
{
return $this->numA + $this->numB;
}

}
@Usage
$addition = new Addition;
$addition->numA = 20;
$addition->numB = 10;
echo $addition(); // 30

Sometime’s we need a controller or class with only a method , this is where __invoke method can be used . Since 5.6.28 , Laravel includes invokable controller also can be called as ‘Single Action Controller’.

We can generate invokable class using the below command .

php artisan make:controller ShowProfile --invokable

The command is pretty much same as we used to make a controller but with an add on of invokable flag ( — invokable ). The generated class will look like this.

<?phpnamespace App\Http\Controllers;use App\User;
use App\Http\Controllers\Controller;
class ShowProfile extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return View
*/
public function __invoke($id)
{
return view('user.profile', ['user' => User::findOrFail($id)]);
}
}

We don’t need to specify the method name.

$this->get('user/profile/{$id}, 'ShowProfile');

Conclusion

If you have any queries or suggestions for us, feel free to drop in your comment. This article is published at laravel-nepal.com .

Happy coding 🙂

Laravel-Nepal

Written by

We share what we learn . Articles and tutorials from laravel developers of Nepal.