SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value

Viewed 11127

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

4 Answers

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.

Add your column name in fillable like this in your model (I guess your model name is Project.php)

So your model class should like this.

<?php

mnamespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
protected $guarded = [];
protected $fillable = [
    'title', 'owner_id','description'
];
public function owner()
{
    return $this->belongsTo(User::class);
}

public function tasks()
{
    return $this->hasMany(Task::class);
}

public function addTask($task)
{
    $this->tasks()->create($task);
}
}

And then update your controller store method like this.

public function store(Request $request)
  {
    $attributes = $this->validateProject();
    $attributes->owner_id = auth()->id();
    $attributes->title = $this->request->title;
    $attributes->description= $this->request->description;
    $project = Project::create($attributes);

      Mail::to($project->owner->email)->send(
        new ProjectCreated($project)
      );

    return redirect('/projects');
  }

The error itself is self explanatory, check this code:

$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);

here you are creating a new record in project table, and for that you are taking only one column i.e. owner_id, but in the table there is a column title which do not have a default value. So either take all the column while creating a new record or provide those column a default value (null or something else).

To set null as default value in migration:

$table->string('title')->nullable();

or you can directly change the column in database and set its default value as null, see the below screenshot:

enter image description here

Unable to trace the problem you are facing. Give this code a try and please comment if you got any problem.

Inside your route file

Route::post('project', 'ProjectController@store')->name('project.store');

In your create view

<form method="POST" action="{{route('project.store')}}">
    @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">
        <div class="control">
            <button type="submit" class="button is-link">Create Project</button>
        </div>
    </div>

    @include('errors')

</form>

In your ProjectController

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;

class UserController extends Controller{
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
        ]);

        $post = Post::create([
                    'title' => $request->title,
                    'owner_id' => auth()->id()
                    ]);

    return redirect('/projects');
  }

EDIT 1

In your previous code inside ProjectsController, instead of using $attributes try using

public function store()
    {
        $project = Project::create([
            'title' => request('title'),
            'owner_id' => request('owner_id')
        ]);

        Mail::to($project->owner->email)->send(
            new ProjectCreated($project)
        );

        return redirect('/projects');
    }

EDIT 2

Instead of using create method, try this one

public function store()
{
        $project = new Project();
        $project->title = request('title');
        $project->owner_id = request('owner_id');
        $project->save();
...
}
Related