Roi
Roi

Reputation: 565

Laravel: How to access the table primary key from result

Model: User
Primary Key: emp_no (alphanumeric)
Fields: password, remember_token

Model: Employee
Primary Key: emp_no (alphanumeric)
Fields: first_name, last_name

Using $users = Users::with('employee')->get();' I could get the list of users with their respective employee record.

I can iterate by

@foreach($users as $user)
    {{ $user->emp_no}} //Not working, always returns 0
    {{ $user->password }} //Working
    {{ $user->remember_token }} //Working
    {{ $user->employee->emp_no}} //Not working, always returns 0
    {{ $user->employee->first_name }} //Working
    {{ $user->employee->last_name }} //Working
@endforeach

As I commented, both attempt to display the emp_no which is the primary key for both table doesn't work.

Upvotes: 0

Views: 743

Answers (1)

sisve
sisve

Reputation: 19781

There's some information lacking, and we chatted for a short while on Laravel's IRC channel. The issue is probably that the model still has $incrementing = true and his primary key is a string. The $incrementing property needs to be set to false.

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.

Source: https://laravel.com/docs/5.4/eloquent

Upvotes: 1

Related Questions