4

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

6
  • Can you please add your validateProject() function? Jun 28, 2019 at 15:39
  • i add a new function at bottom here is complete controller paste.ofcode.org/htHYYDkYnKhgux6azDKtVh –
    – pro
    Jun 28, 2019 at 16:54
  • 1
    What do you get when you dd($request->all()); inside Controller store function? Jun 28, 2019 at 17:23
  • nthing same error
    – pro
    Jun 28, 2019 at 17:46
  • In the first opening line of the store function of the store function. Jun 28, 2019 at 17:48

4 Answers 4

7

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.

5
  • @programmer0001 what is the table structure and what are you passing in your request? Jun 28, 2019 at 13:41
  • @programmer0001 I have updated my answer with the correct $fillable. See if that works? Jun 28, 2019 at 13:47
  • no ssame error m following the laracasts series laracasts.com/series/laravel-from-scratch-2018/episodes/30?autoplay=true
    – pro
    Jun 28, 2019 at 13:49
  • @programmer0001 what is the $this->validateProject(); function? Jun 28, 2019 at 13:51
  • i add a new function at bottom here is complete controller paste.ofcode.org/htHYYDkYnKhgux6azDKtVh
    – pro
    Jun 28, 2019 at 13:53
2

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');
  }
8
  • Undefined property: App\Http\Controllers\ProjectsController::$request
    – pro
    Jun 28, 2019 at 13:51
  • do you have this line use Illuminate\Http\Request; at the top of your controller after namespace ?
    – Fokrule
    Jun 28, 2019 at 13:54
  • yes complete controller: paste.ofcode.org/htHYYDkYnKhgux6azDKtVh
    – pro
    Jun 28, 2019 at 13:55
  • Please use my updated store method. I have updated the code in store method
    – Fokrule
    Jun 28, 2019 at 13:58
  • Let us continue this discussion in chat.
    – Fokrule
    Jun 28, 2019 at 13:59
1

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

1
  • m new to laravel and first time following the laracasts series can u plz show me code about what should i do
    – pro
    Jun 28, 2019 at 13:54
0

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();
...
}
7
  • Class App\Http\Controllers\ProjectController does not exist the name of my controller is ProjectsController
    – pro
    Jun 28, 2019 at 18:03
  • Yes replace ProjectController to ProjectsController Jun 28, 2019 at 18:06
  • Strange. You got the same error after using request('title')? Jun 28, 2019 at 18:13
  • i also have done php artisan migrate:fresh but actually the problem is in controller,,, m following the laracasts series and there he changes a lot code and i think i make any problem during shorten the code because initially it was working but after some changing its not working i have matched the code twice with that video but same error
    – pro
    Jun 28, 2019 at 18:17
  • 1
    404 Sorry, the page you are looking for could not be found.
    – pro
    Jun 28, 2019 at 18:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.