Phillipp Schwarz
Phillipp Schwarz

Reputation: 119

Observer does not work from Command but inside Controller

I am Using Observers in Laravel to add default values to attrbiutes.

public function creating($model)
{
    if (!$model->company_id) $model->company_id = (Auth::check()) ? Auth::user()->company_id : null;
}

This works in every Controller. But if I create a custom Command in app\Console\Commands\. I got an error:

Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value

How do I get Observers working from Command Line?

Upvotes: 0

Views: 376

Answers (1)

Darryl E. Clarke
Darryl E. Clarke

Reputation: 7647

Auth doesn't exist in command line, it's http middleware, so your company_id will always be null. The error is emitted from your database because it is empty and does not have a default value (and is likely not nullable)

Upvotes: 1

Related Questions