Friday, January 28, 2022

[FIXED] Laravel insert default value instead of data sent via request

Issue

I'm facing a peculiar issue on my Laravel app that when I insert data to the database, it always inserts the default value instead of the data sent via a post request. So I dd() the value before inserting them into the database and the correct data showing. But on the database, it always inserts the default value in the migration file.

The same code works fine for another modal.

HTML form

<div class="form-row">
    <div class="col-md-6 mb-3">
        <label for="is_free">Is Free</label>
        <select class="form-control" name="is_free" required>
            <option value="1">Free</option>
            <option value="0">Pro Only</option>
        </select>
        @error('is_free')
        <div class="text-danger mt-2 small ">{{ $message }}</div>
        @enderror
    </div>
</div>

Migration

public function up()
{
    Schema::create('chapters', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('slug');
        $table->string('description');
        $table->mediumText('content');
        $table->tinyInteger('is_free')->default(1);
        $table->timestamps();
    });
}

Controller

Chapter::create([
    'title' => $request->title,
    'slug' => $request->slug,
    'description' => $request->description,
    'content' => $request->content,
    'is_free' => $request->is_free,
]);

Solution

in your Chapter Model, make sure you have $fillable property with correct properties:

class Chapter extends Model
{
 protected $fillable = ['title','slug','description','content','is_free'];
....
}


Answered By - OMR

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.