如何在laravel中将具有用户ID的表格数据插入表中

如何在laravel中将具有用户ID的表格数据插入表中

本文介绍了如何在laravel中将具有用户ID的表格数据插入表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So my create news form is very simple:

  <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处理的:

This is processed by 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的表单中,但是有人可以更改隐藏的字段值.我该怎么做才能正确?

But i have another field, not only title and text body in database, which is author_id and I have no idea how to add info, like the user id from currently authenticated user which wasnt supplied by form. I know how to add hidden input to form with user id, but then someone could change hidden field value. How do I do that correct way?

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

Maybe I have to edit my news eloquent model in some way, which is:

use Illuminate\Database\Eloquent\Model as 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');

}

推荐答案

您始终可以通过Auth::user()获取当前经过身份验证的用户.而且,您还可以在将$data数组传递给create之前对其进行修改.操作方法如下:

You can always get the current authenticated user by Auth::user(). And you can also modify the $data array before passing it to create. Here's how you do it:

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

也不要忘记在fillable属性中添加author_id

Also don't forget to add author_id to the fillable attributes

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

这篇关于如何在laravel中将具有用户ID的表格数据插入表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:42