On my resource controllers I have the usual methods, index store update etc.
I also have a construct that manages middleware and authorization like so:
public function __construct()
    {
        $this->middleware('auth:sanctum')->only(['index', 'update', 'destroy']);
        $this->authorizeResource(User::class, 'user');
    }
On other occasions, such as in single method controllers I just use invoke:
public function __invoke()
    {
        return new UserResource(auth()->user());
    }
If I wanted to add middleware and an authroization policy, should I add it to the invoke method or use a seperate construct method as per my resource contoller detailed above?
A constructor method is executed when a new object instance is created, i.e. when new Something() is being called. In contrast, the __invoke() magic method is called only when the code is trying to call an object as a function (see callbacks / the callable type).
<?php
class CanCallMe
{
  public function __construct()
  {
    echo "Constructor executed.";
  }
  public function __invoke()
  {
    echo "Invoked.";
  }
}
function call(callable $callback)
{
  callback();
}
$callback = new CanCallMe(); // Constructor is executed here.
call($callback); // This is when the __invoke() method will be executed.
Edit: In the context of Laravel  / single action controllers: Middleware (including those defined by the controller) are gathered before the route is run (i.e. __invoke is called). This means middleware added within the __invoke method will not be run. The proof of the pudding is in the eating... Try it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With