我有一个简单的文章模型和一个用户模型.

Article "belongsTo" a User and a User "hasMany" Article.

Therefore my article migration has a foreign key called "user_id".

    Schema::create('articles', function(Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestamps();
    });

然而,每当我在一个隐藏字段中传递"user_id"时,我就会收到一条错误消息.

{!! Form::open(array('route' => 'articles.store')) !!}

    {!! Form::hidden('userId', $user->id) !!}

    <div class="form-group">
        {!! Form::label('title', 'Title') !!}
        {!! Form::text('title', null, array('class' => 'form-control')) !!}         
    </div>

    <div class="form-group">
        {!! Form::label('text', 'Write your Article') !!}
        {!! Form::textarea('text', null, array('class' => 'form-control')) !!}          
    </div>

    {!! Form::submit('Create Article', array('class' => 'btn btn-default btn-success')) !!}
{!! Form::close() !!}

This is the error message. And I understand that I doesn't try to insert the value for the 'user_id' into the articles table.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tags.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into articles (title, body, updated_at, created_at) values (Title, Some text, 2015-03-21 23:19:33, 2015-03-21 23:19:33))

Here is my Store Method on my AriclesController:

    Article::create([
        'title'   => Input::get('title'),
        'body'    => Input::get('text'),
        'user_id' => Input::get('userId')
    ]);

    return Redirect::to('articles');

还有几十个类似标题的开放式Stackoverflow问题,我正在寻找适合我的具体情况的答案,但没有成功,因此我提前向您表示感谢.

How do I save an article into my database?

推荐答案

确保文章模型的fillable属性中有user_id.

http://laravel.com/docs/5.0/eloquent#mass-assignment

Laravel相关问答推荐

密码确认在Livewire中不匹配

自定义验证在表单请求上始终返回 true laravel

阻止用户查看其他用户正在查看的内容的最佳方法是什么?

如何在 Laravel 5 中添加我自己的自定义类?

mysql 加入 ON 和 AND 到 laravel eloquent

在 laravel 5.3 中截断的错误日志(log)

Laravel:如何强制使用 HTTPS?

磁盘 [视频] 没有配置的驱动程序

Eager加载:在具有eloquent关系的枢轴上使用`with`

Laravel 5.4 LengthAwarePaginator

Laravel 4:读取由 javascript 设置的 cookie

如何在 Laravel 中为模型命名,以免与现有类发生冲突?

laravel 5中的配置缓存导致找不到视图

如何在包中安排 Artisan 命令?

控制器中的laravel foreach循环

Eloquent - 带有字符串值而不是列标题的连接子句

Laravel 5如何获取路由动作名称?

如何在 Laravel 中显示动态复选框的旧数据?

Laravel 数据迁移

错误:找不到模块 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' 需要堆栈: