【问题标题】:How do I insert into table form data with user id in laravel?如何在 laravel 中使用用户 ID 插入表格数据?
【发布时间】:2015-02-26 03:24:16
【问题描述】:

所以我的创建新闻表单很简单:

  <div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
  {!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
  <div class="col-md-offset-0 col-md-11">
  {!! Form::text('title', null, ['class' => 'form-control']) !!}
  </div>
</div>
<div class="form-group">
  {!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
  <div class="col-md-offset-0 col-md-11">
  {!! Form::textarea('body', null, ['class' => 'form-control']) !!}
  </div>
</div>
<div class="col-md-offset-5 col-md-3">
  {!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control', 'onclick' => 'this.disabled=true;this.value="Sending, please wait...";this.form.submit();']) !!}
</div>
{!! Form::close() !!}

这是由 NewsProvider 处理的:

    public function store()
{
$validator = Validator::make($data = Input::all(), array(
  'title' => 'required|min:8',
  'body' => 'required|min:8',
));

if ($validator->fails())
{
  return Redirect::back()->withErrors($validator)->withInput();
}

News::create($data);

return Redirect::to('/news');
}

但是我有另一个字段,不仅是数据库中的标题和文本正文,它是 author_id,我不知道如何添加信息,比如来自当前经过身份验证的用户的用户 ID,它不是由表单提供的。我知道如何使用用户 ID 向表单添加隐藏输入,但随后有人可以更改隐藏字段值。我该怎么做?

也许我必须以某种方式编辑我的新闻雄辩模型,即:

use Illuminate\Database\Eloquent\Model as Eloquent;

类新闻扩展了 Eloquent {

  // Add your validation rules here
  public static $rules = [
    'title' => 'required|min:8',
    'body' => 'required|min:8',
  ];

  // Don't forget to fill this array
  protected $fillable = array('title', 'body');

}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您始终可以通过Auth::user() 获取当前经过身份验证的用户。您还可以在将$data 数组传递给create 之前对其进行修改。以下是你的做法:

    $data['author_id'] = Auth::user()->id;
    News::create($data);
    

    别忘了将author_id 添加到fillable 属性中

    protected $fillable = array('title', 'body', 'author_id);
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      相关资源
      最近更新 更多