Home » Php » php – Laravel 5.2 database scheme creates an unique column by it self

php – Laravel 5.2 database scheme creates an unique column by it self

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’ve the following schema for creating the addresses table:

Schema::create('addresses', function (Blueprint $table) {
    $table->string('id')->index();
    $table->string('street', 100);
    $table->integer('number', 5);
    $table->string('addition', 10);
    $table->string('postal_code', 7);
    $table->string('place', 45);
    $table->string('country', 45);
    $table->timestamps();
    $table->softDeletes();
});

For security reasons, ‘id’ is an random generated and unique string instead of an auto increment integer.

Just one problem: Laravel makes the column ‘number’ unique, because it is the only column with data type integer. We want the column ‘id’ as primary and unique key.

We also tried this:

$table->primary('id')->index();
$table->uuid('id')->index();
$table->string('id')->primary()->index();

I’m still getting this error:

Integrity constraint violation: 19 UNIQUE constraint failed:
addresses.number

How to&Answers:

This worked for me:

Schema::create('addresses', function (Blueprint $table) {
      $table->uuid('id')->primary();
      $table->integer('number', false);
  });

Answer:

I had this exact problem. Check out this article: http://garrettstjohn.com/article/using-uuids-laravel-eloquent-orm/

Pretty much what is happening is that Laravel “says” they support UUID’s but they really need a helping hand.

Your schema will work, but just to be sure, I use it as this:

$table->primary('id');

After using the article’s provided examples, you should have something similar to this (this is my User model):

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{

    // UuidForKey is a custom trait added in the app folder
    use SoftDeletes, UuidForKey;

    // This disabled the auto-incrementing
    public $incrementing = false;

    // Make sure id is set as primary
    protected $primaryKey = "id";

    // Makes sure that the id is a string and not an integer
    protected $casts = [
        'id' => 'string',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'password',
        'role',
        'active',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}