Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

subalternate's avatar

Extending Eloquent Models

My current situation is this:

I have a Tasks table that has columns that pertain to a Task such as name, time_to_completion, difficulty, etc. There is an owner of the group of tasks called TaskGroup where the Tasks table has a lookup task_group_id.

I have three standard Tasks that should go inside a TaskGroup... but instead of doing this:

$taskGroup = TaskGroup::create(['name' => 'Tasks']);

$taskGroup->tasks()->create([
    'name' => 'first task',
]);

$taskGroup->tasks()->create([
    'name' => 'second task',
]);


$taskGroup->tasks()->create([
    'name' => 'third task',
]);

I want to be able to extend a Task model and create a specific Task that already has attributes filled, and then add them easily to the group like this:

$taskGroup->tasks()->create([
    (new FirstTask($taskGroup->id)),
    (new SecondTask($taskGroup->id)),
    (new ThirdTask($taskGroup->id)),
]);

Where FirstTask has name = 'First', and other fields already set, so I can make it easier to extend if I ever need more default tasks.

Also, I am passing in the TaskGroup::id to the constructor so it knows how to lookup to its parent.

0 likes
0 replies

Please or to participate in this conversation.