2017-05-30 153 views
2

我正在編寫註釋部分;Laravel沒有將所有數據插入到數據庫

<div class="comment"> 
    <h2>Leave a comment</h2> 
    <form method="post" action="/blog/{{$post->id}}/comments"> 
    {{csrf_field()}} 

    <input type="text" name= "name" class="textbox" value="Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}"> 
    <input type="text" name="email" class="textbox" value="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}"> 
    <textarea value="Message:" name="body" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message</textarea> 

    <div class="smt1"> 
     <input type="submit" value="add a comment"> 
    </div> 
    </form> 
</div> 

我得到的路徑上的那些數據通過CommentsController存儲方法象下面這樣::

Route::post('/blog/{post}/comments','[email protected]'); 

然後經由控制器的方法將它們存儲在DB:我是從下面的表格獲取用戶數據`

public function store(Post $post){ 


    Comment::create([ 
     'body' => request('body'), 
     'email' =>request('email'), 
     'name' =>request('name'), 
     'post_id' => $post->id 
    ]); 


    return back(); 
} 

問題是,當我去數據庫的身體領域插入完全正常,但post_id,名稱,電子郵件他們不插入數據庫,他們是空的。

我已籤,如果我從我做die;dumpdd();nameemail$post->id我得到的數據完全從形成精細的形式獲取數據,但我不能讓他們插在數據庫上?

回答

6

是否在註釋模型中的protected $ fillable數組中列出了post_id,name和email列?如果他們沒有被列爲可填寫的,那麼他們將不會被輸入。

+0

另一個有用的技巧是,如果一切可填寫,設置排除列模型$守衛財產。 –

1

當您在模型上使用create()方法時,您將批量分配字段。因此,您需要將模型中的$fillable屬性設置爲可以分配的所有字段,或者在模型中設置$guarded屬性以防止分配字段。確保你只設置了其中一個屬性,而不是兩個屬性。

在你的情況下,你應該設置可填充屬性。

protected $fillable = [ 
    'name', 'email', 'body', 'post_id' 
]; 

同時,當您創建像這樣的新模型時,您不必擔心質量分配。

$comment = new Comment; 

$comment->body = request('body'); 
$comment->email = request('email'); 
$comment->name = request('name'); 
$comment->post_id = $post->id; 

$comment->save(); 

瞭解更多關於在這裏https://laravel.com/docs/5.4/eloquent