Not work id getter in model (i use uuid type)

I make the primary key as uuid in Model.

Migration with uuid primary key:

Schema::create('brands', function (Blueprint $table) {
    $table->uuid('id')->unique()->primary();
    $table->string('title');
    $table->timestampsTz();
});

Checking model:
Psy Shell

>>> $x = AppModelsBrand::find('e025b8aa-c71e-42ca-b87c-7ee27695b83a');
=> AppModelsBrand {#720
  id: "e025b8aa-c71e-42ca-b87c-7ee27695b83a",
  title: "Batman",
  created_at: "2017-04-28 23:51:41+10",
  updated_at: "2017-04-28 23:51:41+10",
}

When accessing the model, it contains the correct data.
>>> $x->title
=> "Batman"
>>> $x->id
=> 0

Why zero?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Eloquent has some default conventions and thus has some expectations on your model, table, constraints etc…
Luckily, you can change them:

From the Laravel documentation:

Primary Keys

Eloquent will also assume that each table has a primary key column
named id. You may define a $primaryKey property to override this
convention.

In addition, Eloquent assumes that the primary key is an incrementing
integer value, which means that by default the primary key will be
cast to an int automatically. If you wish to use a non-incrementing or
a non-numeric primary key you must set the public $incrementing
property on your model to false.

Regarding your question: “Why zero?”

Because Eloquent casts the string of "e025b8aa-c71e-42ca-b87c-7ee27695b83a" explicitly to an int value and that result is int 0


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x