Hi I am trying to insert data into db but it says:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into
projects
(owner_id
,updated_at
,created_at
) values (1, 2019-06-28 13:17:11, 2019-06-28 13:17:11))
I am following Laracasts Laravel from scratch tutorial
controller:
public function store()
{
$attributes = $this->validateProject();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
//Project::create($attributes);
//Project::create(request(['title', 'description']));
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
model:
protected $guarded = [];
table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('owner_id');
$table->string('title');
$table->text('description');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});
blade file:
<form method="POST" action="/projects">
@csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title" value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
<div class="field">
<label class="label" for="title">Description</label>
<div class="control">
<textarea name="description" class="textarea {{ $errors->has('description') ? 'is-danger' : ''}}" placeholder="Project description">{{ old('description') }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
@include('errors')
</form>
how to solve this issue
You have the field title
on the projects
table however you are not assigning it a value. As it is set as Not Nullable
this will give this error.
You will need all attributes to be in the $fillable
attribute on the model when using Project::create($attributes);
which you do not seem to have.
An example of the $fillable
would be :
protected $fillable = [
'title',
'description',
'owner_id',
];
There are several other potential causes however it is impossible to tell without you including your full Project
model and the view which this request is from.
Edit
You will need to change your function to this :
public function store(ProjectRequest $request)
{
$attributes = $request->all();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
You can create the ProjectRequest
class by running php artisan make:request ProjectRequest
and then putting your validation rules in there instead.
Read more here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With