Laravel: Invokable Controller with specific action
1 min readMay 31, 2020
Have you ever used Laravel Resource controller? Laravel resource routing assigns the typical CRUD routes to a controller with seven methods like, index(), create(), store() etc. Sometimes you need only one method but you are struggling how to name that method. Don’t worry, there’s __invoke() method.
You can generate a Invokable Controller with artisan command
php artisan make:controller ProductController --invokable
Define route in web.php,
Route::get('product/{id}', 'ProductController');
And finally the controller will be,
namespace App\Http\Controllers;
use App\Product;
use App\Http\Controllers\Controller;
class ProductController extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function __invoke($id)
{
return view('product.view', ['product' => Product::findOrFail($id)]);
}
}