简体   繁体   中英

Laravel 5 Model does not insert specified field to database

I'm trying to add captcha to all of my model, but i'm having this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'captcha' in 'field list' (SQL: insert into `deposit_records` (`reference_number`, `deposit_amount`, `deposit_datetime`, `deposit_reference`, `reward_method`, `captcha`, `bank_id`, `deposit_bank`, `deposit_bank_holder`, `deposit_bank_account`, `user_id`, `updated_at`, `created_at`) 

i'm extending custom model class that will auto validate before save, here is the BaseModel.php file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Validator;

class BaseModel extends Model {

    /**
     * Listen for save event
     *
     * @return void
     */
    public static function boot() {
        parent::boot();

        static::creating(function($model) {
            return $model->validate();
        });

        static::updating(function($model) {
            return $model->validate();
        });

        static::saving(function($model) {
            return $model->validate();
        });
    }

    /**
     * Validates current attributes against rules
     *
     * @return boolean
     */
    public function validate() {
        $rules = property_exists($this, 'rules') ? static::$rules : array();
        $messages = property_exists($this, 'messages') ? static::$messages : array();

        if (!empty($rules)) {
            $replace = ($this->getKey() > 0) ? $this->getKey() : null;
            foreach ($rules as $key => $rule) {
                $rules[$key] = str_replace(':id', $replace, $rule);
            }

            $validation = Validator::make($this->attributes, $rules, $messages);
            if ($validation->fails()) {
                $this->errors = $validation->messages();

                return false;
            }
        }

        return true;
    }

    public function error()
    {
        return $this->errors ? $this->errors : null;
    }

    public function errors()
    {
        return $this->errors ? $this->errors : null;
    }

}

and here is the deposit model

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use DB;

class Deposit extends BaseModel {

    use SoftDeletes;

    const REWARD_METHOD_1 = 1;
    const REWARD_METHOD_2 = 2;

    protected $dates = ['deleted_at'];

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'deposit_records';

    protected $fillable = array(
        'reference_number', 'deposit_amount', 'deposit_bank', 'deposit_bank_account', 'deposit_bank_holder', 'deposit_reference', 'deposit_datetime', 'deposit_receipt',
        'bank_id', 'ban_reason', 'deposit_promotion', 'g-recaptcha-response', 'reward_method', 'captcha'
    );

    public static $rules = array(
        'user_id' => 'required|exists:users,id',
        'reference_number' => 'required|min:1',
        'deposit_amount' => 'required|isFund',
        'deposit_bank' => 'required|min:1',
        'deposit_bank_account' => 'required|min:1',
        'deposit_bank_holder' => 'required|min:1',
        'deposit_reference' => 'min:1',
        'deposit_datetime' => 'required|date',
        'deposit_receipt' => 'min:1',
        'bank_id' => 'required|exists:site_banks,id',
        'approve_one_by' => 'exists:users,id',
        'approve_one_at' => 'date',
        'approve_two_by' => 'exists:users,id',
        'approve_two_at' => 'date',
        'ban_by' => 'exists:users,id',
        'ban_at' => 'date',
        'ban_reason' => 'min:1',
        'deposit_promotion' => '',
        'status' => 'in:0,1,2',
        'reward_method' => 'required|in:1,2',
        'captcha' => 'required|isRealPerson',
    );

    public function user() {
        return $this->belongsTo('App\\Models\\User', 'user_id');
    }

    public function depositBank() {
        return $this->hasOne('App\\Models\\SiteBanks', 'id', 'bank_id');
    }

    public function approveOne() {
        return $this->hasOne('App\\Models\\User', 'id', 'approve_one_by');
    }

    public function approveTwo() {
        return $this->hasOne('App\\Models\\User', 'id', 'approve_two_by');
    }

    public function banBy() {
        return $this->hasOne('App\\Models\\User', 'id', 'ban_by');
    }
}

and in my controller, i'm calling like this and it will automatically validate the field and return the error

        $deposit = new Deposit();

        $deposit->fill(Input::all());
        $deposit->deposit_bank = $sb->bank_name;
        $deposit->deposit_bank_holder = $sb->bank_holder;
        $deposit->deposit_bank_account = $sb->bank_account;
        $deposit->user_id = $this->_G['user']->id;

        if ($deposit->save()) {
            addSuccess('Successfully submit deposit request, please wait for verification.');
            return makeJSONResponse(true, 'Successfully submit deposit request, please wait for verification.');
        } else {
            return makeJSONResponse(false, 'Please fix the following error(s).', $deposit->errors->all());
        }

but after i add extra field which is not exists in database, then it keep error for field not found, but i have no idea how can i solve this problem without delete the auto validate, the auto validate is useful and save a lot of time.

IN laravel 4.1, i can do it like the following

//Deposit Model
public function beforeSave() {
    unset($this->{"g-recaptcha-response"});
    unset($this->gRecaptchaResponse);
}

i end up using different method, remove the captcha rules in model, verify it at middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Sentinel;
use Input;

class VerifyCaptcha
{
    public function handle($request, Closure $next)
    {
        if ((Input::has('captcha') && Input::get('captcha') != '') && (Input::has('captchaHash') && Input::get('captchaHash') != ''))
        {
            if (rpHash(Input::get('captcha')) == Input::get('captchaHash')) {
                return $next($request);
            } else {
                return $this->errorResponse($request, 2);
            }
        } else {
            return $this->errorResponse($request, 1);
        }
    }

    public function errorResponse($request, $error) {
        switch ($error) {
            case 1:
                $msg = 'Please keyin the captcha code first';
                break;
            case 2:
                $msg = 'Wrong captcha code';
                break;
            default:
                $msg = 'Unknown error, please refresh and try again';
                break;
        }
        if ($request->ajax()) {
            return makeJSONResponse(false, $msg);
        } else {
            addWarning($msg);
            return redirect()->back()->withInput()->withErrors();
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM