Create Laravel 5 middleware to access route parameters

The question remains why on earth will i ever want to access the route parameter in Laravel 5 middleware? Am sure there are more use case out there, but what i really needed it for, was to check if the authenticated user owns or created a resource, so that they will only be able to view, delete or update the resource if they created it. Am sure you do understand what resource means in the context. If you don’t, simply see resource as a post, user’s profile e.t.c.

So, back to the solution of the proposed question. We would look at the problem in two ways:

  1. When route model binding is used. In this case routes have data bind to them. Now using http://localhost:8000/users/1/edit as an example route, the below middleware checks if the authenticated user is the same as the user with id 1.
<php namespace App\Http\Middleware;

use Closure;
use Auth;

class RedirectIfCannotEdit {

     /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
     public function handle($request, Closure $next)
     {
         $routParameters = $request->route()->parameters();

         foreach ($routParameters as $routParameter) {
             # code...
             if (gettype($routParameter) === "object") {
                 # code...
                 if (isset($routParameter->id)) {
                     # code...
                     $owner = $routParameter->id;

                     if ( $owner !== Auth::id() ) {

                         return redirect('/users/' . Auth::id());

                     }
                 }
             }
         }

         return $next($request);
     }

}

Code Explained

Line 17 gets the route parameters of the request, because a model was bounded on the route, if the model exist the route parameter will be an object representing the model. Line 21 is really not important, it check the resource type of the route parameter. Line 23 is also not very important, it checks if an id exist in the route parameter. Line 27, being the most important part of the code, check if the authenticated user id is the same as the id gotten from the route parameter.

After defining or creating the middleware, we then have to register the middleware by going to app/Http/Kernel.php. If you want this middleware to run during every HTTP request to our application, we would add the middleware class in the $middleware property of our app/Http/Kernel.php. But, if we want to assign the middleware to specific routes, we would then first assign the middleware a short-hand key in the $routeMiddleware property our app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add our own, we would simply append it to this list and assign it a key. I would assign our middleware a key called owner like below:

<php namespace App\Http;

     use Illuminate\Foundation\Http\Kernel as HttpKernel;

     class Kernel extends HttpKernel {

     /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
     protected $middleware = [
         'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
         'Illuminate\Cookie\Middleware\EncryptCookies',
         'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
         'Illuminate\Session\Middleware\StartSession',
         'Illuminate\View\Middleware\ShareErrorsFromSession',
         'App\Http\Middleware\VerifyCsrfToken',
     ];

     /**
     * The application's route middleware.
     *
     * @var array
     */
     protected $routeMiddleware = [
         'auth' => 'App\Http\Middleware\Authenticate',
         'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
         'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
         'owner' => 'App\Http\Middleware\RedirectIfCannotEdit',
     ];

}

Once the middleware has been defined in the HTTP kernel, we may now use our middleware key owner in the route options array like below:


Route::get('posts/1/edit', ['middleware' => 'owner', function()
{
//
}]);

Or you can use it in your controller __consrtuct() function like below:


<php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Post;

class AdminController extends Controller {

public function __construct()
{
    $this->middleware('owner');
}

Know a better way? Please share in the comments box below 🙂