I'll-Be-Back I'll-Be-Back - 11 days ago 6
PHP Question

Best practice to create entry (relationship)?

I am trying to figure out what is best practice to create new row.

Let say we have this in the controller:

$this->noteRepository->addNote($request->user(), $name, $note);


Two working solution of
addNote
method in the
noteRepository
class, for example:

Option 1 - This will create entry using
noteModel


public function addNote($user, $name, $note)
{
return $this->noteModel->create([
'user_id' => $user->id,
'name' => $name,
'note' => $note,
]);
}


Option 2 - there is a
notes()
method in the user model.

public function addNote($user, $name, $note)
{
return $user->notes()->create([
'user_id' => $user->id,
'name' => $name,
'note' => $note,
]);
}


In the
user
model look like this:

public function notes()
{
return $this->hasMany(Note::class);
}


Which is recommended approach to use and why?

Answer

Option 2 looks better with some modification as:

public function addNote($user, $name, $note)
{
     return $user->notes()->create([
         'name'    => $name,
         'note'   => $note,
     ]);
}

It's because you don't have to manually set the FK and it's more elegant and readable. This way you will be utilizing Laravel at the fullest.

Advantages

  • The relationship will be set automatically.
  • The name of the foreign key column doesn't matter (it only needs to be defined in the relationship declaration).