《laravel删除文件;laravel 自定义软删》
在Laravel项目中,文件的删除和自定义软删除是常见的需求。对于文件删除,可以通过Laravel提供的文件系统操作方法来实现;而自定义软删除则可以基于Laravel自带的软删除功能进行拓展。
一、文件删除解决方案
1. 使用Storage facade
这是最常用的方式。例如要删除存储在本地磁盘(默认配置)下的uploads/images/old.jpg
文件:
```php
use IlluminateSupportFacadesStorage;
// 删除文件
if (Storage::exists('uploads/images/old.jpg')) {
Storage::delete('uploads/images/old.jpg');
}
php
如果文件存在多个磁盘中(如同时有本地磁盘和云存储),可以指定磁盘名称:
Storage::disk('custom_disk')->delete('path/to/file.txt');
```
2. 直接使用unlink函数
不过这种方式不推荐,因为它没有利用Laravel优雅的文件系统抽象层。
php
$file_path = public_path('uploads/images/delete_me.jpg');
if (file_exists($file_path)) {
unlink($file_path);
}
二、自定义软删除
1. 修改模型中的软删除字段
默认情况下,Laravel的软删除会在deleted_at字段记录删除时间。我们可以创建自己的字段来实现自定义软删除逻辑。在模型中修改softDelete属性(虽然这不是官方文档推荐的做法,但可以作为一种思路):
php
class MyModel extends Model
{
use SoftDeletes;
const DELETED_AT = 'my_custom_deleted_at'; // 指定自定义字段名
protected $dates = ['my_custom_deleted_at']; // 将其加入日期字段
}
2. 创建自定义软删除trait
更规范的方式是创建一个自定义的软删除trait,在其中重写相关方法,然后在需要的模型中使用这个trait。
```php
<?php
namespace AppTraits;
use IlluminateDatabaseEloquentBuilder;
trait CustomSoftDeletes
{
protected $customDeletedAt = 'customdeletedat';
public function getCustomDeletedAtColumn()
{
return $this->customDeletedAt;
}
public static function bootCustomSoftDeletes()
{
static::addGlobalScope('custom_soft_delete', function (Builder $builder) {
$builder->whereNull($builder->getModel()->getCustomDeletedAtColumn());
});
static::deleting(function ($model) {
if (! $model->forceDeleting) {
$model->{$model->getCustomDeletedAtColumn()} = now();
$model->save();
return false;
}
});
}
public function restore()
{
$this->{$this->getCustomDeletedAtColumn()} = null;
$this->save();
}
}
php
然后在模型中使用:
class MyModel extends Model
{
use CustomSoftDeletes;
}
```
通过以上这些方式,我们可以在Laravel项目中灵活地实现文件删除和自定义软删除功能,以满足不同的业务需求。