PHP code example of spatie / laravel-authorize

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/ */

    

spatie / laravel-authorize example snippets


Route::get('/top-secret-page', [
   'middleware' => 'can:viewTopSecretPage',
   'uses' => 'TopSecretController@index',
]);

Route::group(['prefix' => 'admin', 'middleware' => 'can:viewAdmin'], function() {

   //all the controllers of your admin section
   ...
   
});

Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => 'PostController@edit',
]);

// config/app.php
'providers' => [
    ...
    Spatie\Authorize\AuthorizeServiceProvider::class,
];

//app/Http/Kernel.php

protected $routeMiddleware = [
  ...
  'can' => \Spatie\Authorize\Middleware\Authorize::class,
];

//app/Http/Kernel.php

protected $routeMiddleware = [
    'auth' => 'Spatie\Authorize\Middleware\Authorize',
    ...
];

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;
});

Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => 'PostController@edit',
]);

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);
    }
}

//app/Http/Kernel.php

  protected $routeMiddleware = [
        'can' => 'App\Http\Middleware\Authorize',
        ...
    ];
bash
php artisan vendor:publish --provider="Spatie\Authorize\AuthorizeServiceProvider"