我试图在创建新帖子时保存布尔值,然后在更新帖子时让它更新该值。当我创建新帖子并保存时,它会保留到数据库中,我什至可以毫无问题地更新它。 我只是在处理复选框布尔值时遇到了一些麻烦。这是我在 Laravel 中的第一个项目,我确信这是我的障碍的一部分。
架构
...
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('body')->nullable();
$table->string('photo')->nullable();
$table->boolean('is_featured')->nullable()->default(false);
$table->boolean('is_place')->nullable()->default(false);
$table->string('tag')->nullable()->default(false);
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
...
PostController.php
...
public function store(Request $request)
{
$rules = [
'title' => ['required', 'min:3'],
'body' => ['required', 'min:5']
];
$request->validate($rules);
$user_id = Auth::id();
$post = new Post();
$post->user_id = $user_id;
$post->is_featured = request('is_featured');
$post->title = request('title');
$post->body = request('body');
$post->save();
$posts = Post::all();
return view('backend.auth.post.index', compact('posts'));
}
...
post/create.blade.php
...
<input type="checkbox" name="is_featured" class="switch-input"
value="{{old('is_featured')}}">
...
如果我正确理解问题,您可以将属性转换为模型中的布尔值。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'is_featured' => 'boolean',
'is_place' => 'boolean',
];
}
然后在您的表单中,您需要检查该值以确定是否选中该框。
<input
type="checkbox"
name="is_featured"
class="switch-input"
value="1"
{{ old('is_featured') ? 'checked="checked"' : '' }}
/>
在您的控制器中,您只需检查输入是否已提交。未经检查的输入根本不会被提交。
$post->is_featured = $request
->has('is_featured');
试试这个
$post->is_featured = $request->input('is_featured') ? true : false;
您可以在 Laravel 9+ 中使用
@checked
,如下所示:
@checked(old('is_featured', $post->is_featured))
其中
$post->is_featured
是当会话没有 is_featured
旧值时要发送的后备值或默认值