I have a model Order that stores orders, and has a foreign key team_id that identifies a specific order for a particular team. I used boot() method in a trait to store the team_id automatically:
Every other model works fine, and the data is stored. With this Order model, I get a QueryException from Eloquent: SQLSTATE[HY000]: General error: 1364 Field 'team_id' doesn't have a default value. I don't know what I'm doing wrong. In my $fillable[], I have team_id as fillable.
@Emokores yeah that makes sense as that is where the error originates. I have never set a parameter like that in a hook, but if you say it works on other models, I assume it has to do with the model.
@Sinnbeck Yeah I thought the same thing. I copied and pasted the code in the boot() method of the trait into that of the model and everything works fine.
Just a question: Can you merge two boot() methods in Laravel?
@Sinnbeck Oh, I see! Then using the boot() method of the model is the best solution, and putting all the logic you want there. So now, that model no longer uses the trait, but its boot() method.
@Sinnbeck Wow! This is new! I've just tried this but I have a problem with my editor. It changes the public static function boot() { .. } of the model to public function boot(){ ... } and that gives me an error from Eloquent. I'm using VS Code with Intelephense extension
@Sinnbeck But when I edit the file outside of my editor, everything still works as fine.
use FilterByTeam {
boot as teamBoot;
}
public static function boot()
{
parent::boot(); //* runs the autogenerated stub
// ... <--- boot logic for the model
self::teamBoot(); //* boot logic from the trait
}
@Sinnbeck Actually, your first answer was correct. I think Laravel is opinionated about the naming of the boot() method. I think you have to name it with bootTheAction()
use FilterByTeam {
boot as bootTeamIdentifier;
}
I changed it to this and my editor stopped formatting my static method wrongly, bringing the error.
@anilkumarthakur60 I have team_id in my $fillable[] array. But I have another boot() method in my Order model that autogenerates order numbers (alpha-numeric). Could it be affecting the trait?