【问题标题】:Laravel/Livewire: Use withTrashed() on model route binding on to show deleted recordsLaravel/Livewire:在模型路由绑定上使用 withTrashed() 以显示已删除的记录
【发布时间】:2021-03-04 17:22:12
【问题描述】:

在列表中我显示最新的主题,包括那些被删除的主题。

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 组件的已删除记录?

【问题讨论】:

    标签: laravel eloquent laravel-livewire


    【解决方案1】:

    您可以覆盖 Eloquent 模型上的 resolveRouteBinding() 方法,并有条件地删除 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2021-05-24
      • 2021-09-10
      • 2016-06-04
      • 1970-01-01
      • 2016-04-20
      相关资源
      最近更新 更多