laravel软删除和恢复删除用户
Posted willem_chen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel软删除和恢复删除用户相关的知识,希望对你有一定的参考价值。
laravel软删除和恢复删除用户
1 模型中指定软删除的标识字段
添加代码
use Illuminate\\Database\\Eloquent\\SoftDeletes;
// 调用定义的trait类 和 继承效果一样
use SoftDeletes;
// 软删除标识字段
protected $dates = ['deleted_at'];
文件
<?php
namespace App;
use Illuminate\\Contracts\\Auth\\MustVerifyEmail;
use Illuminate\\Database\\Eloquent\\SoftDeletes;
use Illuminate\\Foundation\\Auth\\User as Authenticatable;
use Illuminate\\Notifications\\Notifiable;
class User extends Authenticatable
{
use Notifiable;
// 调用定义的trait类 和 继承效果一样
use SoftDeletes;
// 软删除标识字段
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
2 添加路由
Route::get('softDeletes', 'JuneController@softDeletes');
3 应用方式
<?php
namespace App\\Http\\Controllers;
use App\\User;
use Illuminate\\Http\\Request;
class JuneController extends Controller
{
public function softDeletes()
{
$user = User::find(request('id'));
// 软删除
// User::find(request('id'))->delete();
// 强制删除 在配置了软删除的时候,真实的删除操作
// User::find($id) -> forceDelete();
# withTrashed()显示所有的,包括已经进行了软删除的
// $user = User::withTrashed()->get();
// 还原
// $user = User::onlyTrashed()->where('id', request('id'))->restore();
return $user;
}
}
以上是关于laravel软删除和恢复删除用户的主要内容,如果未能解决你的问题,请参考以下文章