2

As per title: How can I specify that when trying to save my model (pushing it to the database) that certain columns cannot be null?

e.g. protected $fillable = ['name', 'haircolor'];

I know that I can use a [Mutator][1] but that doesn't work when creating a new object with form data as input, only for individual assingment.

I might use the before save event but that also sounds kinda hacky.

So is there a way to define the constraints in an eloquent model? Or maybe if not, a best practice?

Community
  • 1
  • 1
online Thomas
  • 8,864
  • 6
  • 44
  • 85

1 Answers1

2

Best practice is to define the column as not nullable in migration class by removing ->nullable().

You also could create a wrapper for create() function, like:

public function checkAndCreate($data) {
    // Check if some columns are null and do something about this.
    ....

    return $this->create($data);
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • But how does this help runtime? – online Thomas Jan 12 '17 at 10:06
  • I agree that having the SQL table not nullable is best way to enforce it. Other than that I think `model::saving()` event is safest way to catch-all as it will be triggered every time the event is saving (not only when created). – DevK Jan 12 '17 at 10:12
  • They (we?) should add a special type of exception if the save fails because of constraints in eloquent. That way it's way nicer to handle. I can make it for my dbms (mysql) but general implementation would be awesome. – online Thomas Jan 12 '17 at 10:15