1

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...

Kay
  • 61
  • 3
  • I think instead of `$customer->user()->save($user);` you should use [`associate`](https://laravel.com/docs/8.x/eloquent-relationships#updating-belongs-to-relationships), i.e.: `$customer->user()->associate($user);` – alistaircol Jun 29 '21 at 19:50
  • actually, this part works fine as the database contains all the required information. users.userable_id has the id of customer and users.userable_type has /App/Model/Customer, so this seems to be fine. Nevertheless, thanks, I'll try to use associate instead of save in the future as well. – Kay Jun 29 '21 at 20:07
  • Having a look again, I think you should do `dd($customer->user);` to load the data, you'd use with parentheses if you wanted to do something with the relation, like add an extra where clause or something. – alistaircol Jun 29 '21 at 20:41
  • @alistaircol - you are absolutely right. Don't know how I missed it... Thank you! – Kay Jun 29 '21 at 21:29

0 Answers0