Skip to content

Instantly share code, notes, and snippets.

@trovster
Created November 9, 2015 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trovster/5bae18267e56b0952dd5 to your computer and use it in GitHub Desktop.
Save trovster/5bae18267e56b0952dd5 to your computer and use it in GitHub Desktop.
Laravel 5 Middlewere, using AuthorizesRequests trait but adding a custom message based on action (index, show, destroy etc)
<?php
namespace App\Http\Middleware\Admin;
use Closure;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Models\Site as Model;
class Site
{
use AuthorizesRequests;
/**
* Key for translations.
*
* @var string
*/
public $key = 'site';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->authorize(last(explode('.', $request->route()->getName())), $request->site ?: new Model);
return $next($request);
}
/**
* Authorize the request at the given gate.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function authorizeAtGate(Gate $gate, $ability, $arguments)
{
try {
if($gate->check($ability, $arguments) === false) {
throw new \Illuminate\Auth\Access\UnauthorizedException(trans($this->key . '.' . $ability));
}
return Response();
} catch (UnauthorizedException $e) {
throw $this->createGateUnauthorizedException(
$ability, $arguments, $e->getMessage(), $e
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment