Laravel 9如何切换文章featured字段0/1值实现精选文章功能
Laravel 文章精选状态切换+指定板块展示实现步骤
你现有代码里模型的$fillable配置、数据库字段默认值0的设置已经符合要求,按以下步骤补全逻辑即可:
1. 修正文章创建时的字段赋值逻辑
HTML复选框未勾选时不会向后端传参,你当前的校验逻辑直接取请求参数入库,会导致未勾选精选时字段存null而非预期的0,修改store方法如下:
public function store(Request $request) { $formFields = $request->validate([ 'title' => 'required', 'sub_title' => 'nullable', 'tags' => 'required', 'content' => 'required', 'featured' => 'nullable|boolean', ]); // 手动处理featured值:勾选则存1,未勾选默认存0 $formFields['featured'] = $request->has('featured') ? 1 : 0; Posts::create($formFields); return redirect('/'); }
可选优化:在Posts模型中加字段类型转换,后续判断状态更方便
protected $casts = [ 'featured' => 'boolean', ];
2. 新增状态切换路由
要支持已发布文章的精选状态修改,在路由文件中新增专用路由:
// 切换文章精选状态 Route::post('/posts/{post}/toggle-featured', [PostsController::class, 'toggleFeatured'])->name('posts.toggleFeatured');
3. 编写控制器切换方法
在PostsController中新增状态切换方法,逻辑为直接反转当前文章的featured字段值:
public function toggleFeatured(Posts $post) { // 原有状态取反:0变1、1变0 $post->update([ 'featured' => !$post->featured ]); return back()->with('status', '精选状态更新完成'); }
注意:生产环境请在该方法前加管理员权限校验,禁止普通用户随意修改文章精选状态。
4. 前端添加操作入口
4.1 创建文章页加精选勾选框
在创建文章的表单中加入复选框,支持创建时直接标记精选:
<div class="form-item"> <input type="checkbox" name="featured" id="featured" value="1"> <label for="featured">标记为精选文章</label> </div>
4.2 文章管理列表加切换按钮
在后台文章列表中,为每篇文章加状态切换表单:
<form action="{{ route('posts.toggleFeatured', $post->id) }}" method="POST" style="display:inline"> @csrf <button type="submit"> {{ $post->featured ? '取消精选' : '设为精选' }} </button> </form>
5. 指定板块单独查询并展示精选文章
不要给精选板块传全量文章数据,在对应控制器方法查询时直接过滤出精选内容:
// 普通文章列表 $posts = Posts::latest()->paginate(10); // 精选板块专用数据集:仅取featured=1的文章 $featuredPosts = Posts::where('featured', 1)->latest()->take(5)->get(); return view('站点首页视图名', compact('posts', 'featuredPosts'));
视图中精选板块循环$featuredPosts即可:
<div class="featured-area"> <h3>编辑精选</h3> @foreach($featuredPosts as $post) <div class="post-card"> <h4>{{ $post->title }}</h4> <p>{{ $post->sub_title }}</p> </div> @endforeach </div>
内容的提问来源于stack exchange,提问作者Parit Sawjani
相关产品推荐
相关产品推荐

