phplaravel

Passing a boolean value from checkbox


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.

schema

...
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')}}">
...

Solution

  • If I'm understanding the problem correctly, 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');