所以我的创建新闻表格非常简单:
<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');
}
答案 0 :(得分:1)
您始终可以通过Auth::user()
获取当前经过身份验证的用户。您还可以在将$data
数组传递给create
之前对其进行修改。以下是您的工作方式:
$data['author_id'] = Auth::user()->id;
News::create($data);
另外,不要忘记将author_id
添加到fillable
属性
protected $fillable = array('title', 'body', 'author_id);