Middleware not working as expected - Laravel

- 1 answer

Ad

This is driving me crazy as I think I'm doing the right thing but its not working correctly.

I have a route with a middleware attached to it like below;

Route::get('post/{id}/{name}', '[email protected]')->name('blog-post')->middleware('blogGuard');

As you can see I've defined 2 route params In my controller I have below;

public function post () {
    return view('pages.blog.post');
}

With the middleware defined like this;

public function handle($request, Closure $next)
{

    if (is_null($request->input('id')) ||
        is_null($request->input('name'))) {

        return redirect()->route('blog-home');
    }

    return $next($request);
}

Now if I click on a link like so; http://blog.example.co.uk/post/153/firstpost the middleware should not fire correct?

This is not the case. The middleware executes and I'm redirected. But if I remove the middleware then I'm able to access the page.

Any help appreciated.

Ad

Answer

Ad

If you are trying to access route parameters you probably want to explicitly get them from the route.

$request->route('id');   // pulls the $route->parameter('id');
$request->route('name'); // pulls the $route->parameter('name');

$request->id will check the request inputs before falling back to returning a route parameter. $request->input('id') will only check the input sources for the request and not the route params.

If you use $request->id expecting to get the route param 'id', one could break your logic by passing id=anythinghere to the querystring or adding a 'id' var to a post request.

Ad
source: stackoverflow.com
Ad