Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate content stored in MySQL database submitted by user

Tags:

php

mysql

laravel

I am creating a site that lets users list up to 5 companies they are associated with. When other users search these companies, all users associated with that company will show up in the search results.

The companies will be submitted by the users through a text input field.

How do I avoid users submitting duplicate companies? E.g. if UserA submits a company called stackoverflow, then UserB comes and also submits stackoverflow, there will be 2 stackoverflows in my database.

I have 3 tables:

Users Table

id|username|email

Company Table

id|company name

UsersCompany Table

id|userID|companyID

I'm using Laravel 5

like image 445
Luna Avatar asked Nov 28 '22 14:11

Luna


1 Answers

You should really use Laravel Validation and keyword unique to handle this:

$this->validate($request, [
        'company' => 'required|unique:company|max:255'
]);

Also, you could use custom Request class to handle form validation:

public function rules()
{
    return [
        'company' => 'required|unique|max:255'
    ];
}

If I were you, I'd use second one.

like image 179
Alexey Mezenin Avatar answered Dec 05 '22 23:12

Alexey Mezenin