Laravel Nova – 从观察者手动发送错误警报 Class
Laravel Nova – Manually Send Error Alert From Observer Class
我有一个季节资源模型,其中包含一个名为 active.
的字段
要求是禁止删除处于活动状态的 season
。
我为季节模型创建了一个观察者来观察删除事件。通过这个函数,我可以阻止删除,以防 active
为真。
但问题出在错误信息上;有什么方法可以从 Observer class?
向会话闪存添加错误消息
<?php
public function deleting(Season $season)
{
if($season->active_season)
{
Log::info('Sorry, this season can`t be deleted.
There must be at least one active season.');
}
return false;
}
我不知道如何闪现错误信息。
但由于要求是禁止删除处于活动状态的季节,我建议使用policy,当不符合条件时不会显示删除图标。
class SeasonPolicy {
...
public function delete(User $user, Season $season) {
if($season->active_season) {
return false;
}
return true;
}
}
并在 AuthServiceProvider
中注册策略。
注:
Undefined Policy Methods
If a policy exists but is missing a method for a particular action,
the user will not be allowed to perform that action. So, if you have
defined a policy, don't forget to define all of its relevant
authorization methods.
这没有经过测试,但我能够在之前的项目中实现类似的东西:
use Illuminate\Validation\ValidationException;
class AbcObserver
{
public function creating(Abc $abc)
{
if ($abc->details != 'test') {
throw ValidationException::withMessages(['details' => 'This is not valid.']);
}
}
}
可以使用Exception
class。我在 Nova 操作中对其进行了测试,它会抛出 toast 错误通知。
use Exception;
throw new Exception('Error message here ...');
// Or
throw_if(
$validator->fails(), // or any true boolean
Exception::class,
'Error message here ...'
);
我有一个季节资源模型,其中包含一个名为 active.
要求是禁止删除处于活动状态的 season
。
我为季节模型创建了一个观察者来观察删除事件。通过这个函数,我可以阻止删除,以防 active
为真。
但问题出在错误信息上;有什么方法可以从 Observer class?
向会话闪存添加错误消息<?php
public function deleting(Season $season)
{
if($season->active_season)
{
Log::info('Sorry, this season can`t be deleted.
There must be at least one active season.');
}
return false;
}
我不知道如何闪现错误信息。
但由于要求是禁止删除处于活动状态的季节,我建议使用policy,当不符合条件时不会显示删除图标。
class SeasonPolicy {
...
public function delete(User $user, Season $season) {
if($season->active_season) {
return false;
}
return true;
}
}
并在 AuthServiceProvider
中注册策略。
注:
Undefined Policy Methods
If a policy exists but is missing a method for a particular action, the user will not be allowed to perform that action. So, if you have defined a policy, don't forget to define all of its relevant authorization methods.
这没有经过测试,但我能够在之前的项目中实现类似的东西:
use Illuminate\Validation\ValidationException;
class AbcObserver
{
public function creating(Abc $abc)
{
if ($abc->details != 'test') {
throw ValidationException::withMessages(['details' => 'This is not valid.']);
}
}
}
可以使用Exception
class。我在 Nova 操作中对其进行了测试,它会抛出 toast 错误通知。
use Exception;
throw new Exception('Error message here ...');
// Or
throw_if(
$validator->fails(), // or any true boolean
Exception::class,
'Error message here ...'
);