Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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