2014-12-29 22 views
1

所以我創建的新聞形式非常簡單:如何在laravel中插入帶有用戶標識的表格數據?

<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並且我不知道如何添加信息,例如來自當前已通過身份驗證的用戶的用戶標識,而此用戶標識未由表單提供。我知道如何將隱藏的輸入添加到用戶標識形式,但有人可以更改隱藏的字段值。我該如何做到這一點?

也許我需要編輯在某種程度上我的新聞雄辯模型,它是:

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'); 

} 

回答

1

你隨時都可以通過Auth::user()當前認證的用戶。在將其傳遞給create之前,您還可以修改$data陣列。這裏是你如何做到這一點:

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

另外不要忘記添加author_idfillable屬性

protected $fillable = array('title', 'body', 'author_id); 
相關問題