I am setting up my first Laravel 4 app and the specs call for the id fields to be varchar(36) and be a UUID.
Using Eloquent, my migrations for a sample table looks like this:
Schema::create('users', function($table)
{
$table->string('id', 36)->primary;
$table->string('first_name', 50);
$table->string('last_name', 50);
$table->string('email')->unique();
$table->string('password', 60);
$table->timestamps();
$table->softDeletes();
});
When the users table gets created, the id field is not defined as PK, or unique. It gets defined as varchar(36) NOT NULL.
Why is this happening when I run the migration?
My original question was about using UUIDs, but I have sense solved that by adding this to my Users model in case anyone else sees this post:
protected $hidden = array('password');
protected $fillable = array('id', 'first_name', 'last_name', 'email', 'password');
Here is my route for adding a user (I am using a function to create the UUID):
Route::post('signup', function()
{
$userdata = array(
'id' => gen_uuid(),
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password'))
);
$user = new User($userdata);
$user->save();
return View::make('login/login')->with('userdata', $userdata);
});
You only need some steps to change your Model so use UUID as default. Create Uuid Trait, for example I place the file in App\Traits with name Uuid. php. In this example, we use id column as our primary key, you can use another column as your want.
UUIDs as primary key aren't a slam drunk, but do have some advantages: The fact that they're random means that they don't rely on a single sequence to be generated. Multiple entities can generate IDs independently, but still store them to a shared data store without clobbering each other.
UUIDs are created by your application, so you don't have to wait for the database server to create new users. Since you create your UUIDs independent of the database, you can split your data between multiple database servers. UUIDs are secure, as they're randomly generated and unique, so they can't be guessed.
With your lovely IDE, open the project and go to the 'database/migration' path. If you haven't run migration yet, just modify the user migration file. Or, create another migration file. Change the 'id' type to UUID.
This line
$table->string('id', 36)->primary;
Must be changed to
$table->string('id', 36)->primary();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With