Skip to content

Instantly share code, notes, and snippets.

@Frolki1-Dev
Last active March 22, 2020 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Frolki1-Dev/1c26946fc33681b061ddeb6ee20738f1 to your computer and use it in GitHub Desktop.
Save Frolki1-Dev/1c26946fc33681b061ddeb6ee20738f1 to your computer and use it in GitHub Desktop.
[Laravel] Create for every model a policy file
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class GeneratePoliciesFromModel extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'utils:generate_policies_from_model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create for all models a policy';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Check if a filesystem exists
try {
$disk = Storage::disk('models');
$files = $disk->files();
foreach ($files as $i => $fileName) {
$base = explode('.', $fileName)[0];
// Check if policy exists
if(file_exists(app_path('Policies/' . $base . 'Policy.php'))) {
$this->warn("For model `". $base ."` exists the policy!");
continue;
}
// Create it
$this->call("make:policy", [
"name" => $base . "Policy",
"--model" => "Models/" . $base,
]);
}
} catch (\InvalidArgumentException $e) {
$this->warn($e->getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment