Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel not inserting all data to DB

I am coding a comment section; i am getting user data from the form below:

<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>

I am getting those data on a route via CommentsController store method like below:

Route::post('/blog/{post}/comments','CommentsController@store');

Then storing them on db via controller's method: `

    public function store(Post $post){


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


    return back();
}

the issue is that when I go on the database the body field gets inserted totally fine, but post_id, name, email they dont get inserted on databse, they are empty.

I have checked if I am getting the data from the form I have done die; dump dd(); on name, email and $post->id I get the data totally fine from the form, but I can not get them inserted on the database?

like image 496
Leo Avatar asked May 30 '17 18:05

Leo


2 Answers

Are the post_id, name, and email columns listed in the protected $fillable array in the comment model? If they aren't listed as fillable, then they won't be entered.

like image 137
Sensoray Avatar answered Sep 17 '22 14:09

Sensoray


When you use the create() method on a model, you're mass assigning the fields. Therefore you need to either set the $fillable property in your model with all the fields that can be assigned or set the $guarded property in your model to guard the fields from assignment. Make sure you only set one of these properties and not both.

In your case you should set the fillable property to this.

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

At the same time you don't need to worry about mass assignment when you create a new model like this.

$comment = new Comment;

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

$comment->save();

Read more about it here https://laravel.com/docs/5.4/eloquent

like image 43
Sandeesh Avatar answered Sep 16 '22 14:09

Sandeesh