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

Lizesh Shakya
  • 2,482
  • 2
  • 18
  • 42
pro
  • 609
  • 4
  • 17
  • 40

4 Answers4

6

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.

Kyle Wardle
  • 828
  • 6
  • 23
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');
  }
Fokrule
  • 844
  • 2
  • 11
  • 30
  • Undefined property: App\Http\Controllers\ProjectsController::$request – pro Jun 28 '19 at 13:51
  • do you have this line `use Illuminate\Http\Request;` at the top of your controller after `namespace` ? – Fokrule Jun 28 '19 at 13:54
  • yes complete controller: paste.ofcode.org/htHYYDkYnKhgux6azDKtVh – pro Jun 28 '19 at 13:55
  • Please use my updated `store` method. I have updated the code in `store` method – Fokrule Jun 28 '19 at 13:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195700/discussion-between-fokrule-and-programmer0001). – Fokrule Jun 28 '19 at 13:59
  • Creating default object from empty value this error is at this line $attributes->owner_id = auth()->id(); – pro Jun 28 '19 at 14:00
  • add this line `$attributes = new Project;` before `$attributes->owner_id = auth()->id();` this line – Fokrule Jun 28 '19 at 14:04
  • Undefined property: App\Http\Controllers\ProjectsController::$request – pro Jun 28 '19 at 14:08
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

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • 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 '19 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();
...
}
Lizesh Shakya
  • 2,482
  • 2
  • 18
  • 42
  • Class App\Http\Controllers\ProjectController does not exist the name of my controller is ProjectsController – pro Jun 28 '19 at 18:03
  • Yes replace ProjectController to ProjectsController – Lizesh Shakya Jun 28 '19 at 18:06
  • Strange. You got the same error after using request('title')? – Lizesh Shakya Jun 28 '19 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 '19 at 18:17
  • can you please post the screenshot of dd($attributes);. It seems to be a problem with the $attributes value. dd() just above create function is called. – Lizesh Shakya Jun 28 '19 at 18:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195715/discussion-between-lizeshakya-and-programmer0001). – Lizesh Shakya Jun 28 '19 at 18:21
  • 1
    404 Sorry, the page you are looking for could not be found. – pro Jun 28 '19 at 18:22