簡體   English   中英

Laravel 5模型未將指定字段插入數據庫

[英]Laravel 5 Model does not insert specified field to database

我正在嘗試將驗證碼添加到所有模型中,但出現此錯誤:

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`) 

我正在擴展自定義模型類,該類將在保存前自動驗證,這是BaseModel.php文件

<?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;
    }

}

這是存款模型

<?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');
    }
}

在我的控制器中,我這樣調用,它將自動驗證字段並返回錯誤

        $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());
        }

但是,當我添加數據庫中不存在的額外字段后,它將保持字段未找到的錯誤,但是我不知道如何在不刪除自動驗證的情況下解決此問題,自動驗證非常有用並節省了大量時間。

在laravel 4.1中,我可以像下面這樣

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

我最終使用不同的方法,刪除了模型中的驗證碼規則,在中間件上進行了驗證

<?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();
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM