Skip to content

Instantly share code, notes, and snippets.

@ralphschindler
Last active April 5, 2019 09:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ralphschindler/e4cba393047271efee1d2843bf7629e9 to your computer and use it in GitHub Desktop.
Save ralphschindler/e4cba393047271efee1d2843bf7629e9 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';
});
}
}
@gerardnll
Copy link

gerardnll commented Apr 4, 2019

I would add use Illuminate\Support\Str; on top. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment