Can Anyone help me with policy ?
I have some models inside folder also i created policy incide same named folder so that my folder structure looks good but policy isn't working example
example
models
App\Models\Shop\Example.php
Policies
App\Policies\Shop\ExamplePolicy.php
if i create policy like this policy didn't work in resource
but it works in
App\Models\Shop\Example.php
Policies
App\Policies\ExamplePolicy.php
also works in this
App\Models\Example.php
Policies
App\Policies\ExamplePolicy.php
btw my resource also in filament/resources/shop/
In general if i put my policy in folder it didn't work yes i check namespace and other thing it is correct
so how can i connect resource with policy in this situation
Solution:Jump to solution
By default policy in Filament is actually the policy rule set by Laravel:
https://laravel.com/docs/11.x/authorization#registering-policies
To customize this, go to your
PanelProvider
boot()
method and add something like this:
```
Gate::guessPolicyNamesUsing(function (string $modelClass){...Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
4 Replies
Solution
By default policy in Filament is actually the policy rule set by Laravel:
https://laravel.com/docs/11.x/authorization#registering-policies
To customize this, go to your
PanelProvider
boot()
method and add something like this:
This will follow same policy structure same as in model.Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Ow thanks brother It is working! I didn't know laravel have this kind of function to guess policy class !!
this is the code for my solution!
Gate::guessPolicyNamesUsing(function (string $modelClass) {
// Get the base name of the model class without the namespace
$modelBaseName = class_basename($modelClass);
// Determine the policy class namespace
$policyNamespace = 'App\\Policies\\';
// Handle models in subdirectories by appending the subdirectory to the policy namespace
if (Str::contains($modelClass, 'Models\\')) {
$subDirectory = Str::between($modelClass, 'Models\\', '\\' . $modelBaseName);
if (!empty($subDirectory)) {
$policyNamespace .= str_replace('\\', '\\\\', $subDirectory) . '\\';
}
}
// Construct the full policy class name
$policyClassName = $policyNamespace . $modelBaseName . 'Policy';
return $policyClassName;
});
GENERATED BY CHAT GPT 🐸Ow your solution is better then chat gpt !
Glad I could help!