在列表中,我显示最新主题,包括已删除的主题。
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句