Skip to content

Instantly share code, notes, and snippets.

@luceos
Created May 22, 2015 11:05
Show Gist options
  • Save luceos/180fe5846df81f8b4b8e to your computer and use it in GitHub Desktop.
Save luceos/180fe5846df81f8b4b8e to your computer and use it in GitHub Desktop.
Route Authentication Middleware laravel 5
<?php
trait AuthenticatedTrait
{
/**
* The check to see whether access is allowed to some route
* @return bool
*/
public function allowedToAccessRoute()
{
// your own check that should be used by default
return \Auth::check() && \Auth::user()->id == $this->id;
}
/**
* The redirect or action to undertake when disallowed to access route
* @return \RedirectResponse
*/
public function disallowedRedirectResponse()
{
return \Redirect::route('home');
}
}
<?php namespace App\Http\Middleware;
use Closure;
use Eloquent;
class ModelAuthenticationMiddleware {
public function handle($request, Closure $next)
{
foreach($request->route()->parameters() as $parameter)
{
// chech whether parameter is an eloquent model
if($parameter instanceof Eloquent
// check whether eloquent model implements the AuthenticatedTrait or its own implementation
&& method_exists($parameter, 'allowedToAccessRoute')
// check whether eloquent model implements the AuthenticatedTrait or its own implementation
&& method_exists($parameter, 'disallowedRedirectResponse')
// check whether the user can access the route
&& !$parameter->allowedToAccessRoute())
{
return $parameter->disallowedRedirectResponse();
}
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment