How to pass the value inside the model for checking in the rules

◇◆丶佛笑我妖孽 提交于 2019-12-13 07:42:26

问题


I am trying to have this rules in my model

'Email' =>  'email|unique:tablename,coloumntoignore,ignoreid',

The above rules is to check the unique coloumn except the id to be supplied in the ignoreid

I face two issues here

I am getting the user input

$DriverData = Input::except(array('_token'));

and sending it to the model

$validation  = Validator::make($DriverData, DriverModel::$updaterules);

Note : This update is not the self so i can't get it by Auth::user()->id and my primary key is not id

I check it by

'Email' =>  'email|unique:driver_details,email,4',

It told me error

Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from `driver_details` where `email` = allaudeen.s@gmail.coms and `id` <> 4)

though i mentioned the protected $primaryKey = 'DriverId';

So, How can i have get the value of the field inside the model so that i should check for the rule to check the unique coloumn except its one

Note : The dirty way like putting the DriverId in the session at controller and getting here like that is not preferred.


回答1:


If you're using resourceful routes/controller, the id of the record you're trying to update should be the parameter passed to the update method in the controller.

If you're not using resourceful routes/controller, then the id of the record you're updating needs to be passed in along with the other form data.

As for the validation rule, since your id field is not id, you need to tell the rule that. The fourth parameter to the unique rule is the name of the id field. Documentation on the unique rule is here.

'Email' =>  'email|unique:driver_details,email,4,DriverId',

Once you figure out how you're getting the id of the record you're updating, you will need to figure out how to inject that id into your email rule. Since it looks like your rules are defined as a static attribute on the DriverModel, you may want to take a look at this question/answer here. Basically, you'll need a placeholder in your rule, and then a static method on the model that can replace the placeholder with your specified id:

class DriverModel extends Eloquent {
    public static $updaterules = array(
        'Email' => 'email|unique:driver_details,email,%1$s,DriverId'
    );
    public static function getUpdateRules($id = 'NULL') {
        $rules = self::$updaterules;
        $rules['Email'] = sprintf($rules['Email'], $id);
        return $rules;
    }
}

// usage
$validation  = Validator::make($DriverData, DriverModel::getUpdateRules($id));


来源:https://stackoverflow.com/questions/28205762/how-to-pass-the-value-inside-the-model-for-checking-in-the-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!