从Laravel 5.8表单的复选框传递布尔值

Stu*_*ter 1 php laravel

我尝试在创建新的帖子时保存布尔值,然后在更新帖子时让它更新值。创建新的帖子并保存时,它会持久保存到数据库中,甚至可以更新它而不会出现问题。我在处理复选框布尔值时遇到了一些麻烦。这是我在拉拉韦尔(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');
        });
    }
...
Run Code Online (Sandbox Code Playgroud)

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'));
    }
...
Run Code Online (Sandbox Code Playgroud)

post / create.blade.php

...
<input type="checkbox" name="is_featured" class="switch-input"
       value="{{old('is_featured')}}">
...
Run Code Online (Sandbox Code Playgroud)

mik*_*n32 5

您不清楚问题到底是什么,但是可以在模型中将属性强制转换为布尔值。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $casts = [
        'is_featured' => 'boolean',
        'is_place' => 'boolean',
    ];
}
Run Code Online (Sandbox Code Playgroud)

然后,在表单中,您需要检查该值以确定是否选中了该框。

<input type="checkbox" name="is_featured" class="switch-input" value="1" {{ old('is_featured') ? 'checked="checked"' : '' }}/>
Run Code Online (Sandbox Code Playgroud)

在您的控制器中,您只想检查输入是否已提交。未经检查的输入将不会被加总。

$post->is_featured = $request->has('is_featured');
Run Code Online (Sandbox Code Playgroud)

  • $casts 似乎对我没有任何影响。另外,如果您需要检查“old”然后检查“has”,为什么还要使用它? (2认同)

小智 5

尝试这个 $post->is_featured = $request->input('is_featured') ? true : false;