Tuesday, April 11, 2017

Insert related models: "Field doesn't have a default value"

The character field is filled by a form (dd() proves), but this error is showing up:

General error:

1364 Field 'character' doesn't have a default value (SQL: insert into `characters` (`name`, `user_id`, `updated_at`, `created_at`)

Save or Create?

I try to save another model related to a user. There is form data and internal data. That's why I can't just use the create-method, right? Nobody should be able to manipulate some of these values.

public function store()
{
    // validation

    $character = new Character([
        'user_id' => auth()->id(),
        'character' => request('character'),
        'name' => request('name'),
        'level' => 1,
        'experience' => 0,
        'health' => 500,
        'primary' => 'test',
        'secondary' => 'test',
    ]);
    $user = auth()->user();
    $user->characters()->save($character);

    // redirect
}

My two main questions:

  1. Why would this throw a SQL error pointing to character?
  2. Is this good saving approach, or should I make everything fillable and use create?


via Bensen

Advertisement