I'm trying to add a macro for my query builder so I could have something like this

$person = Person::first(); $person->activity()->log("Newest Activity");

Unfortunately my implementation generates an error

General error: 1364 Field 'person_id' doesn't have a default value

Here is my Implementation,I have a 2 class model,

one is Person Model

public class Person extends Model { public function activity() { return $this->hasMany(Activity::class, "person_id"); } }

and ActivityLog Model

public class ActivityLog extends Model { public function newEloquentBuilder($query) { $builder = parent::newEloquentBuilder($query); $builder->macro('log', function (Builder $builder, $value) use ($query) { return $builder->getModel() ->newInstance([ 'person_id' => // How to get the id from relationship 'details' => $value ]) ->save(); }); return $builder; } }

I know how to do it in laravels way, but I want to avoid specifying keys, this is one of the reason why I am doing this.

How do I access the value of it person_id from the relationship, so that my implementation work?

For more information, my table, this is how my table looks

Person Table | Column | Not Null | Auto Increment | |--------------|----------|----------------| | id | ✓ | ✓ | | first_name | ✓ | | | last_name | ✓ | | | created_at | | | | updated_at | | | Activity Log Table | Column | Not Null | Auto Increment | | id | ✓ | ✓ | | details | ✓ | | | person_id | ✓ | | | created_at | | | | updated_at | | |

My migration for activity log

Schema::create('activity_log', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('person_id'); $table->string('details'); $table->timestamps(); });

For someone, thinking why I am doing this,

this is the second reason why, I am planning to use meta_key, meta_value

here is the sample class

class FavoriteAnimalInfo extends Model { // protected $table = "person_meta"; protected $meta_key_name = 'favorite_animal'; protected static function boot() { parent::boot(); static::creating(function ($model) { $model->meta_key = $model->meta_key_name; }); } public function newEloquentBuilder($query) { $builder = parent::newEloquentBuilder($query); $builder->macro('add', function (Builder $builder, $value) { return $builder->getModel() ->newInstance(['meta_value' => $value]) ->save(); }); return $builder; } }

Now my Person Class Could have something like this

public class Person extends Model { public function favoriteAnimal() { return $this->hasMany(FavoriteAnimalInfo::class, "person_id"); } }

And Now I can EasyLy Do this