1

I want to know if I can add 2 auto-increment columns in the same table in laravel? but the second has different value to start with it?


uniID I want to start from 43600000,

Schema::create('students', function (Blueprint $table){
$table->increments('id');
$table->increments('uniID');
$table->integer('student_id');
$table->timestamps();});
DB::statement("ALTER TABLE students AUTO_INCREMENT = 43600000;");
shrooq
  • 89
  • 1
  • 2
  • 8
  • 3
    Possible duplicate of [How to create two auto increment column in mysql?](https://stackoverflow.com/questions/22824439/how-to-create-two-auto-increment-column-in-mysql) https://dba.stackexchange.com/questions/35449/how-to-use-2-auto-increment-columns-in-mysql-phpmyadmin – Rahul Sep 30 '19 at 13:34
  • Rather than duplicate data in the database - your second field can just be output as the id+43600000. – Nigel Ren Sep 30 '19 at 13:43

1 Answers1

1

Laravel doesn't support this because databases don't generally support it. The increments() and bigIncrements() column types cannot be used multiple times in the same table Schema and will fail on create:

PDOException: SQLSTATE[HY000]: General error: 1 table "students" has more than one primary key

But if uniId will always be 43600000 larger than id, you can use a computed attribute in Eloquent:

class Student
{
    public function getUniIdAttribute()
    {
        return $this->id + 43600000;
    }
}

Then you can use this in your controllers or Blade templates:

>>> $user = Student::first()
=> App\Student{#3078
     id: 1,
     ...
   }
>>> $student->uniId
=> 43600001

The downside to this approach is that you won't be able to use uniId as a foreign key in other tables.

Erich
  • 2,408
  • 18
  • 40
  • can you write your email or anything to allow me to connect with you? – shrooq Oct 01 '19 at 17:07
  • @shrooq feel free to comment here if anything is unclear. or you can ask a new question :) – Erich Oct 01 '19 at 18:15
  • how I can add unique id ? dont say uuid becous it is too long – shrooq Oct 01 '19 at 21:51
  • @shrooq the only thing truly unique is your auto-incrementing primary key. otherwise you could generate a hash from something else unique to the student, like an email address – Erich Oct 02 '19 at 01:55
  • @shrooq or go with a slug-based approach based off first and last names and a number. similar to https://stackoverflow.com/questions/37859974/laravel-how-to-properly-generate-unique-slugs-from-article-titles – Erich Oct 02 '19 at 01:56