vlauciani's avatar

Inheritance on Middleware

Hi all

I'd like to know If is possible to use, and what is the best practice, the Inheritance on Middleware.

For example, I've two routes:

  • route1/input?param1=value1&param2=value2
  • route2/input?param1=value1&param2=value2&param3=value3

then, I've two Middleware:

  • middleware1 for route1
  • middleware2 for route2

but as you can see, the route2 has param1 and param2 equal to route1.

How I can implement the middleware2 to Inheritance the middleware1?

Thank you, Valentino.

0 likes
2 replies
JeroenVanOort's avatar

You could have your two middleware classes extend an abstract middleware class. The handle method of the child classes should call the parent function.

vlauciani's avatar

Something like this?

<?php

namespace App\Http\Middleware;

use Closure;

abstract class AbstractMidClass
{
    public function handle($request, Closure $next)
    {
        if ($request->input('age') <= 20) {
            return redirect('home');
        }       
    {
}
<?php

namespace App\Http\Middleware;

use Closure;
class Middleware1 extends AbstractMidClass
{
    public function handle($request, Closure $next)
    {
        parent::handle($request, Closure $next)
        if ($request->input('weight') <= 80) {
            return redirect('home');
        }       
    }
}
<?php

namespace App\Http\Middleware;

use Closure;
class Middleware2 extends AbstractMidClass
{
    public function handle($request, Closure $next)
    {
        parent::handle($request, Closure $next)
        if ($request->input('height') <= 180) {
            return redirect('home');
        }       
    }
}

Please or to participate in this conversation.