Ok So i am trying to get my head around polymorphism in laravel.
I'm building a site that has 2 different types of users (recruiters, candidates)
They both have some common details which i have created in a user table:
| id | Username | email | password | detailable_id | detailable_type
The rest of the details are going to be very different so i thought i could use polymorphism to help me with this. so i created 2 more tables:
recruiters -> to contain recruiter specific details
candidates -> to contain candidate specific details
I have models for each table
user model:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['username', 'email', 'password'];
protected $hidden = ['password'];
public function detailable()
{
return $this->morphTo();
}
}
Candidate model:
class Candidate extends Model {
public function user()
{
return $this->morphOne('App\User', 'detailable');
}
}
Recruiter model:
class Recruiter extends Model {
public function user()
{
return $this->morphOne('App\User', 'detailable');
}
}
So I did it this way as most tutorials explain it this way (most are explaining how comments can be added onto different objects) This however does not work how i need it to. In this i can do something like $user = App\\Recruiter::find($recruiter_id)->user
to get the user if i have the recruiter id or object. But what i ideally want to be able to do is to say $details = App\\User::find('$user_id')->details
or Auth::user()->details
I really cannot wrap my head around how i would make this work, can anybody help? Or maybe tell me that this cant be done
I feel quite stupid as i have just found the answer in Laravels documentation. You can do what i require with this setup, all i have to do is type Auth::user()->detailable
and this returns the details for the user
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.