you can try where condition on userable() function with morphTo().
And then try your code which you mentioned in addUser() function.
Jul 23, 2022
1
Level 4
One To One Polymorphic Eloquent CRUD Laravel
I have users table and 2 other tables with one to one polymorphic relationship a user can have any one type of profile.
when Users registered first time there is a radio button which select user type insert record into users table how do I add the morphs field into the database according to radio btn follow this doc Laravel 9 https://laravel.com/docs/9.x/eloquent-relationships#one-to-one-polymorphic-relations
// User model
public function userable()
{
return $this->morphTo();
}
// Employee Model
public function user()
{
return $this->morphOne(User::class, 'userable');
}
// Freelancer Model
public function user()
{
return $this->morphOne(User::class, 'userable');
}
How to perform CRUD on userable by user type there will be dropdown for user type
public function addUser()
{
$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('12345678');
$user->type = 'freelancer' or 'employee';
$user->userable()->associate(feelancer());
$user->save();
return $user;
}
User Table https://i.stack.imgur.com/lORjb.png
Employees Table https://i.stack.imgur.com/jImla.png
Freelancers Table https://i.stack.imgur.com/09I2k.png
Please or to participate in this conversation.