Get Route Parameters in Middleware with resource route

880 views Asked by At

It's kinda strange because I followed everything that's online about getting route parameters in the middleware and all of them returns NULL or an error, That's what I already tried and didn't work:

    public function handle($request, Closure $next)
    {
        $token = $request->access_token;
        // Do something with $token
    }

This one returns NULL.

public function handle($request, Closure $next)
    {
        $request->route('parameter_name');
        // Do something with $token
    }

And this one above reurns NULL.

public function handle($request, Closure $next)
    {
        $request->route()->parameters();
        // Do something with $token
    }

And this one above returns:

FatalThrowableError in CheckOwner.php line 22: Call to a member function parameters() on null

What I want is to check if the current user trying to edit a product is the owner of this product based on two thing the id from the 'id' parameter of the URL and the 'user_id' in the products row in the database. and that's my code:

the middleware:

class CheckOwner
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //Get product from $id to edit
        $product = Product::find($request->parameter('product'));
        if ($product->user_id != Auth::user()->id) {
            return redirect('home');
        }
        return $next($request);
    }
}

and that's my route which it's a resource route:

//Products controller show, store, edit, update, destroy
    Route::resource('products', 'ProductsController');

and that's how I registered my middleware in the kernel page:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\CheckOwner::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        /**** OTHER MIDDLEWARE ****/
        'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class
        // REDIRECTION MIDDLEWARE
    ];
}

Right now based on the code above it returns this error:

BadMethodCallException in Macroable.php line 74: Method parameter does not exist.

UPDATE: That's where I use the middleware, in the constructor of the controller:

public function __construct()
    {
        //Kick him/her out if he is not logged in
        $this->middleware('auth', ['except' => ['show']]);
        $this->middleware('checkowner', ['except' => ['create', 'store', 'show', 'update', 'delete']]);
    }
1

There are 1 answers

2
Joseph Silber On

The global middleware run before the route is resolved.

If you need access to route parameters, use your middleware as route middleware:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\CheckOwner::class,
        // the rest of your middleware...
    ],
];