从Laravel 5.8表单的复选框传递布尔值 [英] Passing a boolean value from checkbox in Laravel 5.8 form
问题描述
我尝试在创建新的帖子时保存布尔值,然后在更新帖子时让它更新值.当我创建一个新的帖子并保存时,它会持久保存到数据库中,甚至可以毫无问题地对其进行更新.我在处理复选框布尔值时遇到了一些麻烦.这是我在拉拉韦尔(Laravel)的拳头项目,这是我确定的障碍之一.
I am trying to save boolean value when I create a new Post and then have it update the value if I update the Post. When I create a new Post and save, it persists to the database and I can even update it without issue. I am just having a little trouble dealing with a checkbox boolean. This is my fist project in Laravel, which is part of my hurdle I'm sure.
模式
...
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')}}">
...
推荐答案
You're not very clear on what exactly the problem is, but you can cast the attribute as a boolean in the model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'is_featured' => 'boolean',
'is_place' => 'boolean',
];
}
然后在表单中,您需要检查该值以确定是否选中了该框.
Then in your form you'll want to check that value to determine if the box is checked.
<input type="checkbox" name="is_featured" class="switch-input" value="1" {{ old('is_featured') ? 'checked="checked"' : '' }}/>
在您的控制器中,您只想检查输入是否已提交.未经检查的输入将不会被加总.
In your controller, you'll want to just check if the input is submitted. An unchecked input won't be sumitted at all.
$post->is_featured = $request->has('is_featured');
这篇关于从Laravel 5.8表单的复选框传递布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!