[英]How do I insert into table form data with user id in laravel?
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() !!}
This is processed by NewsProvider: 这是由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');
}
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. 但是我还有另一个字段,不仅是数据库中的标题和文本正文,它是author_id,而且我不知道如何添加信息,例如当前未通过表单提供的经过身份验证的用户的用户ID。 I know how to add hidden input to form with user id, but then someone could change hidden field value. 我知道如何将隐藏的输入添加到具有用户ID的表单中,但是有人可以更改隐藏的字段值。 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;
class News extends 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');
}
You can always get the current authenticated user by Auth::user()
. 您总是可以通过Auth::user()
获得当前经过身份验证的用户。 And you can also modify the $data
array before passing it to create
. 您还可以在将$data
数组传递给create
之前对其进行修改。 Here's how you do it: 这是您的操作方式:
$data['author_id'] = Auth::user()->id;
News::create($data);
Also don't forget to add author_id
to the fillable
attributes 同样不要忘记将author_id
添加到fillable
属性
protected $fillable = array('title', 'body', 'author_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.