How to create Eloquent model with relationship?

0 votes

How to create Eloquent model with relationship?

I have:

Person table

id
firstname
lastname

Employee table

id
person_id
position

I want to do something like this:

Employee::create([
'firstname' => 'Jack',
'lastname' => 'London',
'position' => 'writer'
])

I know, that can create two model and then associate their. But may be there is a way do this more beautiful?

Oct 28 in Laravel by kartik
• 35,300 points
24 views

1 answer to this question.

0 votes

Hello @kartik,

First, you have to create relation in your Person model

class Person extends Model
{
    protected $fillable = ['firstname', 'lastname'];

    public function employee()
    {
        return $this->hasOne('App\Employee');
    }
}

After that in your controller you can do:

$person = Person::create($personData);
$person->employee()->create($employeeData);

Hope it helps!!

Thank You!!

answered Oct 28 by Niroj
• 76,540 points

Related Questions In Laravel

0 votes
1 answer

How to create and Update Laravel Eloquent?

Hello @kartik, There has been a couple of ...READ MORE

answered Nov 11 in Laravel by Niroj
• 76,540 points
45 views
0 votes
1 answer

How can I create a migration to add a value to an enum in eloquent?

Hello @kartik, Try using this code: public function up() ...READ MORE

answered Nov 12 in Laravel by Niroj
• 76,540 points
15 views
0 votes
1 answer

How to make a new page with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
440 views
0 votes
1 answer

How to pass data with routing ?

First you can follow how to pass ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
99 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
3,435 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
411 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 76,540 points
281 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 76,540 points
4,140 views
0 votes
1 answer

How to create custom validation rules with Laravel?

Hii @kartik, Follow are the steps to create ...READ MORE

answered Mar 24 in Laravel by Niroj
• 76,540 points
122 views
0 votes
1 answer

How to manually create a new empty Eloquent Collection in Laravel?

Hello @kartik, It's not really Eloquent, to add ...READ MORE

answered Aug 11 in Laravel by Niroj
• 76,540 points
605 views