Search code examples
laravelinsertauto-increment

Laravel : insert random id on field have autoincrement id


I have generate random id function :

class CreateRandomId {
    public static function get_id($my_table) {
        $id = mt_rand(1000000, 9999999999); 
        if(self::check_id($id,$my_table)){
            get_id($my_table);
        }
        return $id;
    }

    public static function check_id($id,$my_table) {
        $table=DB::table($my_table)->where('id',$id)->get();
        if (count($table)==0) {
            return false;
        }
        return true;
    }
}
 

I used it and it is generate id correctly but when i want to save it as id thus :

$new_user_id = CreateRandomId::get_id('users');   
    $user = User::create([
        'id' => $new_user_id,
        'social_id'=>$request->id, 
        'client'=> $request->client,  
        'username'=>$request->username,
        'password'=>$password,
        'email'=>$request->email,
        'pics'=>$request->pics,
        'role'=>'user'
    ]);

It doesn't save the random id but the auto_incrementid

I view this topic How to disable Laravel eloquent Auto Increment? but I dont want to remove auto increment I just want to insert random data instead of it .


Solution

  • Lets close this question, so as you said in the comments, the fix for this is to make the id field fillable so it looks something like this

    protected $fillable = ['id', ...];