1. Go to this page and download the library: Download spatie/laravel-authorize library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
return [
/*
* The path to redirect for login.
*/
'login_url' => 'auth/login'
];
//only logged in users will be able to see this
Route::get('/top-secret-page', ['middleware' => 'auth', 'uses' => 'TopSecretController@index']);
//only users with the viewTopSecretPage-ability be able to see this
Route::get('/top-secret-page', [
'middleware' => 'can:viewTopSecretPage',
'uses' => 'TopSecretController@index',
]);
//inside the boot method of AuthServiceProvider
$gate->define('update-post', function ($user, $post) {
return $user->id === $post->user_id;
});
use Symfony\Component\HttpKernel\Exception\HttpException;
...
protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
{
if ($request->ajax()) {
return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);
}
if (!$request->user()) {
return redirect()->guest(config('laravel-authorize.login_url'));
}
throw new HttpException(Response::HTTP_UNAUTHORIZED, 'This action is unauthorized.');
}
//app/Http/Middleware/Authorize.php
namespace App\Http\Middleware;
use Spatie\Authorize\Middleware\Authorize as BaseAuthorize;
use Symfony\Component\HttpFoundation\Response;
class Authorize extends BaseAuthorize
{
protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
{
return reponse('I am a teapot.', Response::HTTP_I_AM_A_TEAPOT);
}
}