Created
November 9, 2015 16:33
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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