Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.