输入字段未在数据库中更新

Input field not updating in the database

我正在做一个 laravel 5.2 项目。我从 Posts.

引用 category_id

我的Post模型看起来像

class Post extends Model
{

    protected $fillable=['category_id '];


    public function category(){

        return $this->belongsTo('App\category');
    }
}

此外,我的表格看起来像

<div class="form-group">
    {!! Form::label('category_id','Category:') !!}
    {!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}

</div>

我的table数据

 @foreach($posts as $post)
    <tr>

        <td>{{$post->category['name']}}</td>
    </tr>
@endforeach

问题是,每当我创建一个新的 post 时,类别名称不会保存在数据库中,也不会显示在前端。

我的 Post 架构 table

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->index()->unsigned()->nullable();

});

即使我 dd() post table 上类别 ID 的输入字段也是空的。有人可以帮我解决这个问题,这让我发疯了。谢谢

我正在使用资源控制器,这是我的创建请求控制器

 public function store(Request $request)
    {
        $user=Auth::user();
        $input = $request->all();
         Post::create($input);
        return redirect('admin/posts');
    }

这是因为可填写字段只是category_id尝试在您的可填写字段上添加类别名称字段。

//this are the fields that is fillable
protected $fillable=['category_id','name'];

有了这个类别名称字段将能够捕获和保存数据。

仔细检查您的可填写字段和输入字段是否相同。

你的关注点你只显示这个。

<div class="form-group">
    {!! Form::label('category_id','Category:') !!}
    {!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}

</div>

其他领域呢。我们希望你也已经在你的表格上了。

<div class="form-group">
    {!! Form::label('input_name','Name:') !!}
    {!! Form::input('name',old('name'),['class'=>'form-control', 'id' => "input_name"]) !!}

</div>

在你的存储方法中它应该是这样的

  $new_post = new Post;
   $new_post->category_id = Input::get(‘category_id’);
$new_post->name = Input::get(‘name’);
$new_post->save();

以防万一你没有使用 $request

的填充方法

继续我的评论。您的迁移应如下所示。

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->index()->unsigned()->nullable();
        $table->string('category_name')->nullable();

});

您的模特,

class Post extends Model
{

    protected $fillable=['category_id','category_name'];

}

表格

<div class="form-group">
    {!! Form::label('category_id','Category:') !!}
    {!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}
    {!! Form::input('category_name',old('category_name'),['class'=>'form-control', 'id' => "input_name"]) !!}

</div>

最后,您的 table 数据应如下所示。

@foreach($posts as $post)
    <tr>
        <td>{{$post->category_name}</td>
    </tr>
@endforeach

为了访问您关系的属性,您应该:

 $post->comment->name;

并尝试在保存时使用'fill()'

 $post = new Post;
 $post->fill($request->all());
 $post->save();

我在我的表单中使用这个修复了错误。

{!! Form::select('category_id', [''=>'choose Categories'] + $categories,['class'=>'form-control']) !!}
这是我的 table.

<td>{{$post->category['name']}}</td>

感谢大家的努力。