Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fhdalikhan/3c33ddfc45cd31f9740774a7df862eb4 to your computer and use it in GitHub Desktop.
Save fhdalikhan/3c33ddfc45cd31f9740774a7df862eb4 to your computer and use it in GitHub Desktop.
Laravel 5.8 Policy Guesser For Using "Models" Directory
<?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