I am developing a web application using Laravel. I am using Nova for admin panel. What I am doing now is I am authorizing my resource using policies as mentioned in the documentation. But seems like it is not working. This is what I have done so far. I have created a nova resource like this.
class Item extends Resource
{
/**
* The model the resource corresponds to.
*
* @var string
*/
public static $model = \App\Models\Item::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* @var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
];
}
/**
* Get the cards available for the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function actions(Request $request)
{
return [];
}
}
Then I created a Laravel Model class for that resource with the name Item.
Then I created policy.
class ItemPolicy
{
use HandlesAuthorization;
public function viewAny(User $user)
{
return true;
}
public function view(User $user, $item)
{
return true;
}
public function create(User $user)
{
return false;
}
public function update(User $user, $item)
{
return false;
}
public function delete(User $user, $item)
{
return false;
}
public function restore(User $user, $item)
{
return false;
}
public function forceDelete(User $user, $item)
{
return false;
}
}
I register the policy in the in AuthServiceProvider.
protected $policies = [
Item::class => ItemPolicy::class,
];
When I see the list of item in the nova admin panel, I can still create the item. What is wrong? The option for creating an item should be hidden.
Add the following to your Nova resource class:
public static function authorizable()
{
return true;
}
Check AuthServiceProvider once again.
where you define the policy mapping array:
protected $policies = [
Item::class => ItemPolicy::class,
];
The Item - should be your Model, not Nova Resource
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With