DEV Community

Fersho Pls
Fersho Pls

Posted on

How to pass non-string parameters to Middleware Laravel

<?php

namespace App\Domains\AppFeatures\Middleware;

use App\Domains\AppFeatures\AppFeatures;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class AppFeatureMiddleware
{
    public function __construct(
        protected AppFeatures|array $features,
        protected null|User         $user = null,
    )
    {
    }

    public static function make(AppFeatures|array $features, User $user = null)
    {
        $id = uniqid();
        app()->bind($id, fn () => new static($features, $user));
        return $id;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(
        Request $request,
        Closure $next,
    )
    {
        if (!AppFeatures::has($this->features, $this->user)) {
            abort(404);
        }

        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode
Route::middleware(
AppFeatures::middleware(AppFeatures::CAN_CREATE_CLIENTS)
)->get('/test', fn() => 'Hello World');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)