How to compare data from a phpmyAdmin DB with form data laravel

I am inserting data into a phpmyAdmin DB(using laravel). How can I restrict a user from adding duplicate data into a particular table? for example: a username. every user should have a unique username. If a user enters a username that already exist, they should get an error(preferably with session) saying the username already exist. Thanks for the help in advance

$detailscode = DB::Table('products')->select('description_code')->where('id',1)->get();              foreach ($detailscode as $items){         $codes = $items;      } if($request->detailscode == $codes){          Session::put('Error','Enter a different code');          return redirect::to('/add-product');       } 
Add Comment
1 Answer(s)

In your migration you can tell SQL to prevent duplicate, like this :

$table->string('username')->unique(); 

Now you cant insert same username on this table, if you try to do you will get error message from SQL.

To prevent the error show on your Laravel app, you need to use validation :

$validator = Validator::make($request->all(), [     'username' => 'unique:users,username',  ]); 

See official documentation here

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.