Laravel 5 : multi-model middleware "Owner" -
i want create middleware check if authenticated user owner of item. single model, code easy , :
<?php namespace app\http\middleware; use closure; class owner { public function handle($request, closure $next) { $id = $request->segments()[1]; //get id parameter $model = model::find($id); // find model db if(!$item) return 'not found'; //if item not found //check if authenticated user owner if($item->user_id == \auth::id()){ return $next($request); }else{ return 'not allowed'; } } }
now let's have multiple models (modelx, modely, modelz) , don't want rewrite middleware handle function several times. how 1 inject referenced model in middleware make accomodate multiple models app?
you use middleware parameters route/model binding. lets assume have post resource.
you define route. middleware gets parameter describing resource want check ownership of.
route::get('/post/{post}', ['middleware' => 'owner:post', 'as' => 'post', 'uses' => 'postcontroller@showpost']);
then bind model in routeserviceprovider.php:
$router->bind('post', function ($value) { return post::where('id', $value)->firstorfail(); });
finally make middleware. important know binding becomes available in request object $request->post. since you're passing name of resource middleware, becomes third parameter in handle method.
public function handle($request, closure $next, $resource) { if ($request->{$resource}->user_id == \auth::id()) { return $next($request); } return response('not allowed.', 401); }
i suppose programmatically find resource name, using method resource name , route can different.
Comments
Post a Comment