PHP code example of soulcodex / model-keyable

1. Go to this page and download the library: Download soulcodex/model-keyable 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/ */

    

soulcodex / model-keyable example snippets


use Illuminate\Database\Eloquent\Model;
use Soulcodex\Keyable\Keyable;

class Account extends Model
{
    use Keyable;

    // ...
}

// ...

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware(['api', 'auth.apikey'])
	->namespace($this->namespace . '\API')
	->group(base_path('routes/api.php'));
}

// ...

use App\Http\Controllers\Controller;

class FooController extends Controller {

    public function index(Request $request) 
    {
        $model = $request->keyable;

        // ...
    }

}

return $model->foo()->get();


	
return [
	
    'allow_empty_models' => true
	
];



return [

    'identifier' => 'bigint'
    
];


	
return [
	
    'modes' => ['header'],
	
    'key' => 'X-Authorization',
	
];


	
return [
	
    'modes' => ['parameter'],
	
    'key' => 'api_key'
	
];

https://example.com/api/posts?api_key=<key>



namespace App\Http\Controllers;

// ...

use Soulcodex\Keyable\Auth\AuthorizeKeyableRequest;

class Controller extends BaseController
{
    use AuthorizeKeyableRequest;
}



namespace App\Policies\KeyablePolicies;

use App\Models\Post;
use Illuminate\Database\Eloquent\Model;
use Soulcodex\Keyable\Models\ApiKey;

class PostPolicy {

    public function view(ApiKey $apiKey, Model $keyable, Post $post) {
    	return !is_null($keyable->posts()->find($post->id));
    }
    
}



namespace App\Providers;

// ...

use App\Models\Post;
use App\Policies\KeyablePolicies\PostPolicy;
use Soulcodex\Keyable\Facades\Keyable;

class AuthServiceProvider extends ServiceProvider
{
	
    // ...
    
    protected $keyablePolicies = [
        Post::class => PostPolicy::class
    ];

    public function boot(GateContract $gate)
    {
        // ...
        Keyable::registerKeyablePolicies($this->keyablePolicies);
    }
    
}



namespace App\Http\Controllers\PostController;

use App\Models\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller {

    public function show(Post $post) {
        $this->authorizeKeyable('view', $post);
        // ...
    }

}
bash
php artisan vendor:publish --provider="Soulcodex\Keyable\KeyableServiceProvider"
bash
php artisan migrate
bash
php artisan api-key:generate --id=1 --type="App\Models\Account"
php artisan api-key:generate --id='6324d582-5614-430b-a35c-c24b621a93c5' --type="App\Models\Account"
bash
php artisan api-key:delete --id=12345
php artisan api-key:delete --id='6324d582-5614-430b-a35c-c24b621a93c5'