You need to enable JavaScript to run this app. Laravel 8 如何自动填充数据库表的created_by与updated_by字段
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 如何自动填充数据库表的created_by与updated_by字段

解决方案

先修正现有代码的已知问题

  • Post模型的$fillable字段配置错误:你写的is-active和表结构的is_active不匹配,同时需要补充updated_by、user_id到可批量赋值字段中,否则操作时会报错
  • 现有Controller中created_by的赋值逻辑错误:User::where('name')->get()缺少where条件参数,且get()返回的是用户集合,不符合字段字符串类型的要求,后续我们用自动填充逻辑直接替换这部分代码即可

方案一:模型Boot方法自动填充(单模型场景推荐,实现最简单)

直接修改Post模型代码,通过模型事件监听新增、更新操作,自动填充对应字段:

class Post extends Model
{
    use HasFactory;

    protected $table = 'posts';    

    // 修正后的可批量赋值字段
    protected $fillable = [
        'post_title', 
        'post_slug', 
        'post_thumbnail', 
        'post_seq', 
        'post_excerpt', 
        'post_description', 
        'post_meta_title', 
        'post_meta_description', 
        'post_meta_keyword', 
        'is_active', 
        'created_by',
        'updated_by',
        'user_id'
    ];

    // 新增boot方法注册事件监听
    protected static function boot()
    {
        parent::boot();

        // 监听新增操作,自动填充创建人、更新人
        static::creating(function ($post) {
            if (auth()->check()) {
                // 如果你要存用户ID就替换为 auth()->id()
                $post->created_by = auth()->user()->name;
                $post->updated_by = auth()->user()->name;
            }
        });

        // 监听更新操作,自动填充更新人
        static::updating(function ($post) {
            if (auth()->check()) {
                $post->updated_by = auth()->user()->name;
            }
        });
    }

    public function scopeSearch($query, $title)
    {
        return $query->where('post_title', 'LIKE', "%{$title}%");
    }
}

修改完成后直接删除Controller的Post::create数组里的created_by赋值代码即可,后续新增、更新操作都会自动填充两个字段。

方案二:观察者实现(多模型通用场景推荐)

如果你的项目中多个表都需要自动填充创建人、更新人字段,用观察者统一管理更易维护:

  1. 生成观察者文件,执行命令:
    php artisan make:observer PostObserver --model=Post
  2. 编辑app/Observers/PostObserver.php代码:
namespace App\Observers;

use App\Models\Post;
use Illuminate\Support\Facades\Auth;

class PostObserver
{
    public function creating(Post $post)
    {
        if (Auth::check()) {
            $post->created_by = Auth::user()->name;
            $post->updated_by = Auth::user()->name;
        }
    }

    public function updating(Post $post)
    {
        if (Auth::check()) {
            $post->updated_by = Auth::user()->name;
        }
    }
}
  1. 在app/Providers/AppServiceProvider.php的boot方法中注册观察者:
public function boot()
{
    \App\Models\Post::observe(\App\Observers\PostObserver::class);
}

两种方案任选其一即可实现需求,无登录用户场景下auth()->check()返回false,不会给字段赋值,符合你表结构中两个字段nullable的配置。

内容的提问来源于stack exchange,提问作者Sutan Firqy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:06:03