laravel - Laravel/Livewire:在模型路由绑定上使用 withTrashed() 以显示已删除的记录
问题描述
在列表中,我显示最新主题,包括已删除的主题。
function latest()
{
return Topic::withTrashed()->latest();
}
为了显示单个主题,我有一个 Livewire 组件,其中传递了该主题。
class ShowTopic extends Component
{
public $topic;
public function mount(Topic $topic)
{
$this->topic = $topic;
}
public function render()
{
return view('livewire.show-topic', [
'topic' => $this->topic,
]);
}
}
但是,当我转到已删除的单个主题时,它不会显示。如何withTrashed()
在模型路由绑定上使用 Livewire 组件显示已删除的记录?
解决方案
您可以覆盖resolveRouteBinding()
Eloquent 模型上的方法,并有条件地删除SoftDeletingScope
全局范围。
在这里,我使用该模型的策略来检查我是否可以delete
使用该模型 - 如果用户可以删除它,他们也可以看到它。您可以实现您想要的任何逻辑,或者如果这更适合您的应用程序,则可以删除所有请求的全局范围。
use Illuminate\Database\Eloquent\SoftDeletingScope;
class Topic extends Model {
// ...
/**
* Retrieve the model for a bound value.
*
* @param mixed $value
* @param string|null $field
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value, $field = null)
{
// If no field was given, use the primary key
if ($field === null) {
$field = $this->getKey();
}
// Apply where clause
$query = $this->where($field, $value);
// Conditionally remove the softdelete scope to allow seeing soft-deleted records
if (Auth::check() && Auth::user()->can('delete', $this)) {
$query->withoutGlobalScope(SoftDeletingScope::class);
}
// Find the first record, or abort
return $query->firstOrFail();
}
}