
Generate unique username in Laravel
You can generate the unique username in Laravel from user's name. Here we will create the username and will also take care of that the record with same username is not already exists in users table.
Answers 1
-
Generate unique username from user's name while creating user in Laravel
//routes\web.php Auth::routes(); //app\Models\User.php use Illuminate\Support\Str; protected $fillable = [ 'name', 'email', 'password', 'username' ]; public function generateUserName($name){ $username = Str::lower(Str::slug($name)); if(User::where('username', '=', $username)->exists()){ $uniqueUserName = $username.'-'.Str::lower(Str::random(4)); $username = $this->generateUserName($uniqueUserName); } return $username; } //app\Http\Controllers\Auth\RegisterController.php protected function create(array $data) { $userObject = New User; $userName = $userObject->generateUserName($data['name']); return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'username'=>$userName, ]); } //Create a username column in the users table. ALTER TABLE `users` ADD `username` VARCHAR(200) NOT NULL AFTER `remember_token`;
0
Random Code Snippet Queries: Laravel
- Laravel onclick function not working
- Laravel pagination links with query string
- How to print form data in laravel
- Skip first n record and display rest records in laravel view
- Send OTP using textlocal api in laravel
- Get laravel version
- SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'posts_user_id_foreign'; check that column/key exists
- Update email with unique validation in laravel
- How to run a specific seeder class in laravel
- Rename Pivot Table in Laravel
- How to customize pagination view in laravel
- Delete records with relationship in laravel
- Laravel recursive function in controller
- Ignore Records where a field has NULL value in Laravel
- How to get all posts which contains comments in laravel
- SQLSTATE[42000]: Syntax error or access violation: 1055
- How to check duplicate entry in laravel
- Class 'App\Http\Controllers\User' not found
- Get posts belongs to a specific user in Laravel
- Insert Comma Separated Values in laravel
- How to check column value of a record is null or not in laravel
- Calculate age from date of birth in Laravel
- Submit form without CSRF token in Laravel
- How to remove package from laravel
- How to create laravel project using composer