Solution:
When you use
a class you are just importing it for use in that file so that you don’t have to use the entire path when you want to reference it – think of it as an alias. It is also worth noting that the full class path is not the same as the relative class name in a file. The full class path will always contain the full namespace!
When you are setting up relationships Eloquent needs the full class path so that it can build objects when operating in it’s own namespace. You can use ::class
on any class to get the full class path, which in your case is App\Models\UserProfile
.
Take the following examples:
- Eloquent will think the the relation class is
\UserProfile
which doesn’t exist.public function profileDetails() { return $this->hasOne('UserProfile', 'user_id', 'id'); }
- Eloquent will look for the class
\App\Models\UserProfile
which does exist!public function profileDetails() { return $this->hasOne('App\Models\UserProfile', 'user_id', 'id'); }
- Eloquent will look for the class
\App\Models\UserProfile
which does exist! This is the most reliable way to reference other classes.public function profileDetails() { return $this->hasOne(UserProfile::class, 'user_id', 'id'); }