-
-
Save gurindersingh/4058fb0f8e59483aec9cd0688055f040 to your computer and use it in GitHub Desktop.
Laravel 5.8 Policy Guesser For Using "Models" Directory
This file contains hidden or 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\Providers; | |
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; | |
use Illuminate\Support\Facades\Gate; | |
class AuthServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Register any authentication / authorization services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
$this->registerPolicies(); | |
/** | |
* generate a Policy class name in the App\Policies namespace | |
* | |
* 1) keep the model heirarchy if it is App\Models: | |
* example: App\Models\Foo\Bar -> App\Policies\Foo\BarPolicy | |
* | |
* 2) fallback and provide App\Policies for non-App\Models: | |
* example: Laravel\Nova\Actions\ActionEvent -> App\Policies\ActionEventPolicy | |
*/ | |
Gate::guessPolicyNamesUsing(function ($modelClass) { | |
return Str::startsWith($modelClass, 'App\Models') | |
? 'App\Policies\\' . str_replace('App\Models\\', '', $modelClass) . 'Policy' | |
: 'App\Policies\\' . class_basename($modelClass) . 'Policy'; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment