Laravel中is_active布尔值无法正确保存到数据库问题咨询
Laravel布尔值is_active始终保存为0问题修复方案
问题根因
三个错误点共同导致该问题:
- Post模型的
$fillable属性中字段名拼写错误:你写的是中划线格式的is-active,但实际数据库字段和请求参数都是下划线格式的is_active,Laravel的批量赋值保护会自动过滤不在$fillable列表里的字段,导致is_active的值根本没被写入,直接使用了数据库默认值0 - 控制器中
is_active赋值逻辑错误:你用了$request->has('is_active'),这个方法的作用是判断请求中是否存在该参数,你用下拉框提交的场景下,不管选True还是False,is_active参数都会被正常提交,该判断逻辑完全无效 - 额外错误:
created_by的赋值逻辑错误,User::where('name')->get()缺少where条件参数,且get()返回的是用户集合,不能直接存入单个字段
修复步骤
第一步:修正Post模型的$fillable字段
把is-active改成is_active,同时补充需要批量赋值的user_id字段:
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', 'user_id']; public function scopeSearch($query, $title) { return $query->where('post_title', 'LIKE', "%{$title}%"); } }
第二步:修正控制器store方法的赋值逻辑
直接使用请求中的is_active值即可,不需要额外用has判断,同时修正created_by的赋值逻辑(以下示例为存储当前登录用户的name,可根据自身需求调整):
public function store(Request $request) { $request->validate([ 'post_title' => 'required|string|max:60', 'post_slug' => 'required|string|unique:posts,post_slug', 'post_thumbnail' => 'required', 'post_excerpt' => 'required|string|max:500', 'post_seq' => 'required', 'post_description' => 'required|string', 'post_meta_title' => 'required|string|max:60', 'post_meta_description' => 'required|string|max:250', 'post_meta_keyword' => 'required|string', 'is_active' => 'required|boolean' // 可新增boolean验证规则规范输入 ]); Post::create([ 'post_title' => $request->post_title, 'post_slug' => $request->post_slug, 'post_seq' => $request->post_seq, 'post_thumbnail' => parse_url($request->post_thumbnail)['path'], 'post_excerpt' => $request->post_excerpt, 'post_description' => $request->post_description, 'post_meta_title' => $request->post_meta_title, 'post_meta_description' => $request->post_meta_description, 'post_meta_keyword' => $request->post_meta_keyword, 'created_by' => auth()->user()->name, 'is_active' => $request->is_active, 'user_id' => $request->user_id ]); Alert::success('Add Post', 'Added Post Success'); return redirect()->route('posts.index'); }
可选优化
可以在Post模型中添加$casts属性,把is_active自动转为布尔类型,更方便后续业务逻辑判断:
protected $casts = [ 'is_active' => 'boolean', ];
内容的提问来源于stack exchange,提问作者Sutan Firqy
相关产品推荐
相关产品推荐

