Insert row in parents and childs table laravel

Viewed 854

Im so lost. I have table, model and controller named Navbar. Here I create navbar buttons. I made child table called "type_1". So "navbar" id goes to table "type_1" and its column called "navbar_id".

        $form_data = array(
        'tipas'    => $tipas,
        'p_id'     => $p_id,
        'name'     => $request->title,
        'text'     => $request->text,
        'img'      => $name
    );

    navbar::create($form_data); //created parent row

Here navbar button is created. How can I create childs empty row with parent (navbar) id? Should I use models or I can do it here?

1 Answers

On your Parent model, you need to define a relation like this :

public function child()
{
    return $this->hasMany(Child::class);
}

Now you can insert data with eloquent method like this :

$form_data = array(
  'tipas' => $tipas,
  'p_id' => $p_id,
  'name' => $request->title,
  'text' => $request->text,
  'img'  => $name
);

$q = Parent::create($form_data); //created parent row
$q->child()->create(['name' => 'John', 'email' => 'me@john.com']); // here parent_id will be created by the model

Official documentation of the create method

Related