What are invokable controllers
There are times when as a laravel developer you need to create a controller without CRUD functionalities that being no seven resourceful methods, like index(), create(), store() etc.
This means you just need a controller that performs one action, Well good news laravel comes with a method for this thus _invoke method. Since Laravel 5.6.28, you can create a Controller with only one method __invoke():
namespace App\Http\Controllers;
use App\Models\Product;
use App\Http\Controllers\Controller;
class ProductController extends Controller
{
/**
* Show the Product.
*
* @param int $id
* @return Response
*/
public function __invoke($id)
{
return view('products.product', ['product' => Product::findOrFail($id)]);
}
}
As you can see, you can also pass a parameter to id.
To call that method+Controller, in your routes/web.php you should have this:
Route::get(product/{id}’, ‘ProductController’);
You can also generate this kind of Controller, with this Artisan command:
php artisan make:controller ProductController — invokable
summary
If a controller in Laravel has just one action then you simplify the controller by using the
invoke()
method.
Before you go… Thanks for reading the article! If you enjoyed it, please don’t forget to show your appreciation by clicking 👏 below!
Any questions or comments hit me up on
Mail: epmnzava@gmail.com
Twitter: https://twitter.com/epmnzava
Github: https://github.com/dbrax