You can ignore an id :
'username' => 'required|unique:staff_user,username' . $this->id
No good I'm afraid even with the missing comma after the username field that does not work, it still reverts to checking for an 'id' field in the database.
You can specify the primary key name and other fields to ignore with the unique rule, just read the doc.
Of course you should have the extra conditions on update, and should not have them on create, i misread your question. I agree it's a bit strange but it is the way to go.
I like to do it this way :
$username = ($this->username) ?: 'NULL';
public $rules = array(
'forename'=>'required|alpha|min:2',
'surname'=>'required|alpha|min:2',
'upn' => 'required|unique:staff_user',
'username' => "required|unique:staff_user,username,$username,username"
);
the snippet above doesnt work ? Whats the error ?
The SQL query it generates is garbage, I can get it to work if I reference the other unique field in the table so:
$this->rules['username'] = "required|unique:staff_user,username,{$this->username},upn,$upn";
With upn being the other unique field in the db and that creates the following query:
select count(*) as aggregate from `staff_user` where `username` = username and `upn` <> upn
That seems to make more sense, as the originally generated query would always evaluate to false..
Ok. of course I was wrong :
"required|unique:staff_user,username,$username,username"
Is a nonsense because you want the username to be unique across the staff_user table without the lines that contains this username... So the rule is always respected. You should stick to the conventions and add an id field to this table, then when updating you can exclude the corresponding line as I shown earlier.
I had similar update problem where I had users table with primary key as username and also a unique email field. What I did was ....
'username' => 'required|max:20|unique:users,username,'.$user->username.',username',
'email' => 'required|email|max:60|unique:users,email,'.$user->username.',username',
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community