Register a new type of user in laravel 5.5 - laravel-5.5

I encounter an error in my register page of user in laravel 5.5 like below:
****SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "tb_users_user_name_key"\n
DETAIL: Key (user_name)=(user_deo) already exists. (SQL: insert into "tb_users" ("name", "user_name", "phone", "email", "password", "default_password", "updated_at", "created_at") values (doe, user_deo, 017244668, sample#gmail.com, $2y$10$96qs6iC6HVbBZ2rtfNcsg.DiBjA14g/k9DQPzFWqXSh153sZCuUPy, 123456, 2018-06-18 01:47:36, 2018-06-18 01:47:36) returning "user_id")****
with validation fields of user like this:
Validator::make($data, [
'name' => 'required|string|max:255',
'user_name' => 'required|string|unique:tb_users,user_name',
'phone' => 'required|string|unique:tb_users,phone',
'email' => 'required|string|email|unique:tb_users,email',
'password' => 'required|string|min:6|confirmed',
]);
I just want to know why Validation unique column in Laravel, is not work. It should pass error messages from Validation to register form back.

Could it be because you already have the user_name of "user_deo" in your database? Thus getting a unique violation.

Related

Django MongoDB Model field with unique values or null

I am using Djongo v1.3.6 to connect Django to MongoDB. Now I would like to have an optional field for a unique value - in my case a phone number. I thought it is possible to have null as a placeholder for accounts that do not have a phone number. However, MongoDB seems to be treating null as a unique value as well. Thus, it is not letting me insert new objects into the database once one object has phone_number: null
I tried to declare the index for phone_number as sparse but it does not seem to take any effect. I searched the Internet for some time now but could not find anything useful for my case.
class UserProfile(models.Model):
user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE)
phone_number = models.CharField(validators=[PHONE_VALIDATOR], max_length=17, unique=True, null=True, blank=True)
...
meta = {
'indexes': [
{'fields': ['phone_number'], 'sparse' : True, 'unique' : True},
],
}
Any help is very appreciated.
I solved this issue altering the index that is created by Djongo using pymongo.
from pymongo import MongoClient, database, collection
collection.drop_index(index_name)
index_name = rchop(index_name, '_1')
collection.create_index(
[(index_name, pymongo.ASCENDING)],
partialFilterExpression = {
index_name : { "$exists" : True, "$gt" : "0", "$type" : "string" }
}
)
Once I had altered the index, I was able to insert null values into MongoDB without sacrificing the unique check for non-null values

Django IntegrityError manytomany field

I'm trying to implement hashtags in my django app
I have a message model with a field like this
hash_tags = models.ManyToManyField(HashTag, related_name='message_hash_tags')
And this is the HashTag model
hash_tag = models.CharField(max_length=140, primary_key=True)
And I'm setting the hashtags to the message like this
hash_tags_list = Functions.extract_hashtags(message["message"])
hash_tags = [HashTag.objects.get_or_create(hash_tag=ht) for ht in hash_tags_list]
messageObj.hash_tags.set(hash_tags)
messageObj.save()
But this errors out
django.db.utils.IntegrityError: insert or update on table "messaging_message_hash_tags" violates foreign key constraint "messaging_message_ha_hashtag_id_068959e9_fk_messaging"
DETAIL: Key (hashtag_id)=((<HashTag: HashTag object (skills)>, True)) is not present in table "messaging_hashtag".
Tho I can find the HashTag object (skills) in my messaging_hashtag table:
SELECT * FROM messaging_hashtag;
hash_tag
----------
skills
get_or_create returns a tuple which contains the object and a flag on whether the object was created or not, so something like: (obj, created)
To fix this, just extract the obj from the tuple. For example using [0] on the result:
hash_tags = [ HashTag.objects.get_or_create(hash_tag=ht)[0] for ht in hash_tags_list ]

Django: null value in column "created_at" violates not-null constraint

I'm trying to add records via the code below:
Post.objects.update_or_create(
user=user,
defaults={
"title": external_post.get('title'),
"body": external_post.get('body'),
"seo": external_post.get('seo')
}
)
I've successfully migrated the model but I'm getting the error " null value in column "created_at" violates not-null constraint".
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I faced this same problem when I was using the #transaction atomic decorator in Django. Basically the reason why I faced the same error was that I was not using the default auto-increment ID in one of my models but rather I had specified a particular field as the primary key using primary_key=True
As a result my data contained two primary keys that were the same. This resulted in an 'update' operation rather than a 'create' operation in the database.
So, Django was trying to update an entry but the created_at field was missing hence the error.
I would suggest you do this instead:
post,created = Post.objects.update_or_create(
user=user,
defaults={
"title": external_post.get('title'),
"body": external_post.get('body'),
"seo": external_post.get('seo')
})
if created:
# your code goes here
#(this ensures that the code is executed only if an entry is getting created in the database)
You can read this for a better explaination: https://code.djangoproject.com/ticket/17654

Doctrine Native Query does not load related entities even if I add addMetaResult mapping

I have 2 tables:
users - id, firstName, lastName
posts - id, title, content, user_id
I'm trying to load entities with native query:
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entity\Post', 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addFieldResult('p', 'title', 'title');
$rsm->addMetaResult('p', 'user_id', 'user_id');
$sql = 'select p.id, p.title, p.user_id from posts p';
$query = $em->createNativeQuery($sql, $rsm);
$posts = $query->getResult();
Doctrine loads "Post" entity, and fills "User" relation, but all attributes of "User" entity is NULL. Why it doesn't load "User" entity with proxy object? For what does "addMetaResult" exists?
Actually if you call get_class on "User", than you'll see that it is a doctrine proxy. All attributes are nulls because proxy is not loaded. Call on of "getter" methods (for example getFirstName()) on one of attribute and doctrine will load class and fill all other attributes.

Testing Model Save

I'm trying to do a very basic test:
public function testUsernameIsRequired(){
$user = new User;
$user->email = "phil#ipbrown.com";
// User should not save
$this->assertFalse($user->save());
}
on the following model:
class User extends Eloquent implements UserInterface, RemindableInterface {
use SoftDeletingTrait;
protected $fillable = array('email', 'username', 'password');
public static $rules = array(
'email' => 'required|min:3',
'username' => 'required|min:3',
'password' => 'required|min:3'
);
}
According to my thinking (...yeah) this test should succeed, as a User model which gets saved without required fields doesn't actually save.
But this Model somehow does save, doesn't throw any errors and creates a completely empty User.
Any ideas as to what I'm doing wrong?
$rules is just something you made up - it wont work out of the box like that. You need to actually validate the models against the rules to enforce it on save.
Laravel 4 - Trouble overriding model's save method will do what you want without Ardent.