1
votes

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into posts (title, body, updated_at, created_at) values (?, ?, 2019-10-14 17:41:00, 2019-10-14 17:41:00))

controller (CRUD) controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
 use App\post;
class postcontroller extends Controller
{


    public function store(Request $request)
    {

    $add = new post;
    $add->title= $request->input('title');
    $add->body= $request->input('body');;
    $add->save();

    session()->flash('msg','new post added successfully!');

    return redirect()->route('posts.show',$add->id);
    }

Model (post model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class post extends Model
{


     protected $fillable = ['title', 'body'];
}

view ->(it just a from using laravelcollective )

1
Your title is empty, and your database schema does not allow your title to be nullable. Check your view to make sure it's sending the title correctly (input name='title')Raul

1 Answers

1
votes

It looks like you are sending null value for the title and to catch out the validation errors earlier on in your application, you should consider introducing some validation in your controller

    <?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\post;

class postcontroller extends Controller
{
    public function store(Request $request)
    {
       $request->validate([
        'title' => 'required',
        'body' => 'required',
       ]);

       $add = Post::create([
          'title' => $request->input('title'),
          'body'  => $request->input('body')
       ]);

        session()->flash('msg','new post added successfully!');

        return redirect()->route('posts.show', $add->id);
    }

Make sure you have set the title and body fields in your form correctly

<form><!-- / Dont forget the action, crf and other required attr of form -->

   <input type="text" name="title">
   <textarea name="body"></textarea>
</form>

Learn more about form validation at https://laravel.com/docs/master/validation#validation-quickstart