Let's assume I've got a User model ("users" table => id, email, userable_id, userable_type) and a Customer model ("customers" table => id, name etc., not important fields).
User model has the following:
public function userable()
{
return $this->morphTo();
}
Customer model has the following:
public function user()
{
return $this->morphOne('App\Models\User', 'userable');
}
Everything works fine when I create new Customer and assign a user account to it like this:
$customer->user()->save($user);
However, when I'm trying to get a user information for a particular customer like this:
$customer = Customer::findOrFail($id);
dd($customer->user());
I expect it to have any information regarding the corresponding user account for a particular customer. But it doesn't return any! dd returns the following:
Illuminate\Database\Eloquent\Relations\MorphOne {#1488 ▼
#morphType: "users.userable_type"
#morphClass: "App\Models\Customer"
#foreignKey: "users.userable_id"
#localKey: "id"
#query: Illuminate\Database\Eloquent\Builder {#1493 ▶}
#parent: App\Models\Customer {#1487 ▶}
#related: App\Models\User {#1494 ▼
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
#isOneOfMany: false
#relationName: null
#withDefault: null
What do I do wrong? Went over several topics on Stack Overflow and thoroughly red Laravel documentation, but just can't understand what's wrong...