SQLSTATE [23000]:违反完整性约束:1048列“ category_id”不能为空

时间:2019-04-30 23:17:57

标签: php laravel-5

我想创建一个带有categery_id的帖子,作为发布/创建表单的下拉列表,但是我得到一个SQLSTATE [23000]:完整性约束违规:1048列'category_id'不能为空(SQL:插入{{ 1}}(poststitlebodycategory_idauthor_idupdated_at)...

我需要一点帮助来找出导致此问题的原因,这是到目前为止我所拥有的...

create.blade.php

created_at

PostController.php

    @extends('layouts.app')
        @section('content')
         <div class="container">
         <h1>Create Post</h1>
          <div class="row post_row">

       {!! Form::open(['action' => 'PostsController@store', 'method' => 'POST', 'class' => 'form']) !!}
      <div class="col-md-8">           
         <div class'form-group'>
           {{ Form::label('title', 'Title')}}
           {{ Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title'])}}
         </div>
      </div>

      <div class="col-md-4">
        <div class'form-group'>
           {{ Form::label('categories_id', 'Category :')}}
             <select class='form-control' title="category_id">
               @foreach ($categories as $category => $value)
                <option value="{{$value->id }}">{{ $value->title }}</option>
               @endforeach
            </select>
        </div>
      </div>
</div>

<div class="row post_row">
   <div class="col-md-8">
     <div class'form-group'>
       {{ Form::label('body', 'Body')}}
       {{ Form::textarea('body', '', ['id' => 'article-ckeditor', 'class' => 'form-control space', 'placeholder' => 'Body Text'])}}
     </div>
  </div>
</div>

   <div class'form-group' style="padding-top: 20px">
      {{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
      {!! Form::close() !!}
  </div>
</div>  

@endsection

Post.php     

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;
use App\Category;


class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    protected $limit = 3;

    public function create()
    {
    $posts = Post::all();
    $categories = Category::all();

    return view('posts.create')->with(['posts' => $posts, 'categories' => $categories]);
}


public function store(Request $request)
    {
        $this->validate($request, [
        'title' => 'required|max:255',
        'body' => 'required'
        ]);
        //create Post
        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->category_id = $request->input('category_id');
        $post->author_id = auth()->user()->id;
        $post->save();

    return redirect('/posts')->with('success', 'Your post created created successfully');
}

public function update(Request $request, $id)
{
        $updated = Category::findorFail($id);
        $categories = $request->all();
        $category_id = $request->get('category_id');
        $updated->fill($categories)->save();

    return redirect('/dashboard')->with('success', 'Your post created updated successfully');
}

Category.php     

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use GrahamCampbell\Markdown\Facades\Markdown;

class Post extends Model
{
    //Table Name
protected $table = 'posts';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;

protected $fillable = [
    'title',
    'excerpt',
    'body',
    'categery_id',
    'image',

];

protected $dates = ['published_at'];


public function author()
{
    return $this->belongsTo(User::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

public function getImageUrlAttribute($value)
{
$imageUrl = "";

if( ! is_null($this->image))
{
    $imagePath = public_path() . "/img/" . $this->image;

    if(file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}

return $imageUrl;

}

public function getDateAttribute()
{
    return is_null($this->published_at) ? '' : $this->published_at->diffForHumans();    
}

public function getExcerptHtmlAttribute()
{
    return $this->excerpt ? Markdown::convertToHtml(e($this->excerpt)) : NULL;
}

public function getBodyHtmlAttribute()
{
    return $this->body ? Markdown::convertToHtml(e($this->body)) : NULL;
}

public function scopeLatestFirst($query)
{
    return $query->orderBy('published_at', 'desc');
}

public function scopePublished($query)
{
    return $query->where('published_at', '<=', Carbon::now());
}

}

CreatePostsTable.php     

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
protected $table = 'categories';

protected $fillable = [
    'title',
    'categery_id'
];

public function posts()
{
    return $this->hasMany(Post::class);
}

public function getRouteKeyName()
{
    return 'slug';
}
}

这就是我到目前为止所拥有的,没有人知道为什么我遇到这个问题吗?

1 个答案:

答案 0 :(得分:0)

认为出现此问题是因为在CreatePostsTable迁移中类别ID不能为空。您可以像这样将其设置为可空值。

$table->integer('category_id')->nullable()->unsigned();