I want to create a middleware to check if the authenticated user is the owner of the item. For a single model, the code is easy and would look something like :
<?php namespace App\Http\Middleware;
use Closure;
class Owner {
public function handle($request, Closure $next)
{
$id = $request->segments()[1]; //get the id parameter
$model = Model::find($id); // find the model from DB
if(!$item)
return 'not found'; //if item not found
//check if authenticated user is owner
if($item->user_id == \Auth::id()){
return $next($request);
}else{
return 'not allowed';
}
}
}
Now let's say I have multiple models (ModelX, ModelY, ModelZ) and I don't want to rewrite the middleware handle function several times. How would one inject the referenced model in the middleware to make it accomodate multiple models from my app?
You could use route and middleware parameters:
Here’s the middleware (
app/Http/Middleware/AbortIfNotOwner.php
):Inside
app\Http\Kernel.php
:Inside your route file (
app/Http/routes.php
):And optionally call it in the controller: