jacobkdick's avatar

$model->save() not saving but no error

When updating my Post model, I run:

$post->title = request('title');
$post->body = request('body');

$post->save();

This does not update my post. But it should according to the Laravel docs on updating Eloquent models. Why is my model not being updated?

  • I get no errors.
  • The post does not get updated in the db.
  • Besides not being updated in the db, nothing else seems odd. No errors. Behavior as normal.
  • Result of running this test to see if save succeeded was true.
  • This Laravel thread was no help

Post model:

class Post extends Model
{
    protected $fillable = [
        'type',
        'title',
        'body',
        'user_id',
    ];

   ....
}

Post controller:

public function store($id)
{
    $post = Post::findOrFail($id);

    // Request validation
    if ($post->type == 1) {
        // Post type has title
        $this->validate(request(), [
            'title' => 'required|min:15',
            'body' => 'required|min:19',
        ]);

        $post->title = request('title');
        $post->body = request('body');
    } else {
        $this->validate(request(), [
            'body' => 'required|min:19',
        ]);

        $post->body = request('body');
    }

    $post->save();

    return redirect('/');
}

Bonus info

Running dd($post->save()) returns true.

Running

$post->save();

$fetchedPost = Post::find($post->id);
dd($fetchedPost);

shows me that $fetchedPost is the same post as before without the updated data.

0 likes
20 replies
vivekdhumal's avatar

@jacobkdick did you specified primary key in model

protected $primaryKey = "post_id" // default it look for id
2 likes
mushood's avatar
mushood
Best Answer
Level 41

@jacobkdick

At first look, all looks good in the code you've shown. Can you also post the form? Maybe you are sending the same value

Here is also what you can do to check it the information is correct

public function store($id)
{
    $post = Post::findOrFail($id);

/* check initial data */
dump($post);

    // Request validation
    if ($post->type == 1) {
        // Post type has title
        $this->validate(request(), [
            'title' => 'required|min:15',
            'body' => 'required|min:19',
        ]);

        $post->title = request('title');
        $post->body = request('body');

/*check request information */
/*check if the data passed from the form is correct */
dump(request('title'));
dump(request('body'));
        
/* check updated data */
dump($post);

    } else {
        $this->validate(request(), [
            'body' => 'required|min:19',
        ]);

/*check request information */
/*check if the data passed from the form is correct */
dump(request('body'));

        $post->body = request('body');

/* check updated data */
dump($post);
    }

    $post->save();

/* stop the flow so you can check the dumps */
die();

    return redirect('/');
}

From the above code, you can follow the flow of the update.

jacobkdick's avatar

@mushood following the path with the dumps. $post->save() updated the $post object so that both the attributes and the original on the dump contained the updated code. But the database still didn't contain the updated values.

mushood's avatar

@jacobkdick Then I would say that the connection to the database is incorrect. Are you able to create post objects and save them to the database?

As a test, run this:

     /* Harcode the ID of the post  */
    $id = X;
    $post = Post::findOrFail($id);

    /* Harcode the title and the body */
    $title = "test";
    $body = "test";

    if ($post->type == 1) {

        $post->title = $title;
        $post->body = $body;
    } else {

        $post->body = $body;
    }

    $post->save();

    return redirect('/');

If after this code, the database is not updated, then the error comes from your database connection.

If its actually the case, try checking out this thread

https://laracasts.com/discuss/channels/eloquent/check-to-see-if-i-can-connect-to-a-database?page=1

Snapey's avatar

do you have a choice of databases?

jacobkdick's avatar

@mushood

Hardcoding the $post attributes didn't do anything different. The saving still did not work.

I followed the thread you pointed me to and I am definitely connected to the database. I am able to create new posts with different test users and read posts by anyone.

@Snapey Yes.

Snapey's avatar

What I mean is, are you looking at the database that the application is updating? A common mistake is to have a database in Homestead and locally and be confused about which is being updated.

1 like
jacobkdick's avatar

@Snapey yes I have confirmed that I am referencing the same database. I only have 1 database connected.

Snapey's avatar

ok, could you be updating one record but checking another? Is there are mistake in passing of the id

Cronix's avatar

The store method is usually to create a new post, not edit an existing one. Are you sure you're hitting the correct route and didn't mean update?

jacobkdick's avatar

@Snapey the table only has 10 records in right now in testing. Along with the dumps, I have checked the database and I'm confident that the correct post is being found and passed through the function.

@Cronix although my naming convention is not best practice (my first project...I'll change it!) I'm sure that this function is being hit. I've been troubleshooting with the store function.

jacobkdick's avatar

@Snapey

Here are the results from tinker:

>>> $post = \App\Post::find(10);
=> App\Post {#769
     id: 10,
     post_type_id: 1,
     accepted_answer_id: null,
     parent_id: null,
     score: 0,
     view_count: 1,
     body: "Mostly to see if I can even still post a question...",
     owner_user_id: 2,
     owner_username: null,
     last_editor_user_id: null,
     last_editor_username: null,
     last_edit_date: null,
     last_activity_date: null,
     title: "This will be a test question",
     tags: null,
     answer_count: 0,
     comment_count: 0,
     favorite_count: 0,
     closed_date: null,
     community_owned_date: null,
     created_at: "2017-10-28 01:33:14",
     updated_at: "2017-10-28 01:33:14",
   }
>>> $post->title = "This is changed now";
=> "This is changed now"
>>> dump($post);                                                                                                                                                                                                                  
App\Post {#769
  #searchableColumns: array:2 [
    0 => "title"
    1 => "body"
  ]
  #fillable: array:5 [
    0 => "post_type_id"
    1 => "title"
    2 => "body"
    3 => "owner_user_id"
    4 => "parent_id"
  ]
  #guarded: array:1 [
    0 => "id"
  ]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:22 [
    "id" => 10
    "post_type_id" => 1
    "accepted_answer_id" => null
    "parent_id" => null
    "score" => 0
    "view_count" => 1
    "body" => "Mostly to see if I can even still post a question..."
    "owner_user_id" => 2
    "owner_username" => null
    "last_editor_user_id" => null
    "last_editor_username" => null
    "last_edit_date" => null
    "last_activity_date" => null
    "title" => "This is changed now"
    "tags" => null
    "answer_count" => 0
    "comment_count" => 0
    "favorite_count" => 0
    "closed_date" => null
    "community_owned_date" => null
    "created_at" => "2017-10-28 01:33:14"
    "updated_at" => "2017-10-28 01:33:14"
  ]
  #original: array:22 [
    "id" => 10
    "post_type_id" => 1
    "accepted_answer_id" => null
    "parent_id" => null
    "score" => 0
    "view_count" => 1
    "body" => "Mostly to see if I can even still post a question..."
    "owner_user_id" => 2
    "owner_username" => null
    "last_editor_user_id" => null
    "last_editor_username" => null
    "last_edit_date" => null
    "last_activity_date" => null
    "title" => "This will be a test question"
    "tags" => null
    "answer_count" => 0
    "comment_count" => 0
    "favorite_count" => 0
    "closed_date" => null
    "community_owned_date" => null
    "created_at" => "2017-10-28 01:33:14"
    "updated_at" => "2017-10-28 01:33:14"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
}
=> null
>>> $post->save();
=> true
>>> $post = \App\Post::find(10);
=> App\Post {#776
     id: 10,
     post_type_id: 1,
     accepted_answer_id: null,
     parent_id: null,
     score: 0,
     view_count: 1,
     body: "Mostly to see if I can even still post a question...",
     owner_user_id: 2,
     owner_username: null,
     last_editor_user_id: null,
     last_editor_username: null,
     last_edit_date: null,
     last_activity_date: null,
     title: "This will be a test question",
     tags: null,
     answer_count: 0,
     comment_count: 0,
     favorite_count: 0,
     closed_date: null,
     community_owned_date: null,
     created_at: "2017-10-28 01:33:14",
     updated_at: "2017-10-28 01:33:14",
   }

Even using tinker, I can't get it to save.

Snapey's avatar

can you please show your entire Post model?

1 like
newbie360's avatar

i didn't read all the comments here, but i have a same problem before

no error no new record stored to database

i keep read my code and dd() still don't know what happened

dd($post); // $post has data and no problem
$post-save();

finally find out what happened

my old database table look like this, useless_column1 ans 2 IS NO DEFAULT VALUE

id | name | nick | useless_column1 | useless_column2

my model

class MyModel extends Model
{
    protected $guarded = [];
}

i forgot delete the useless_column1 and useless_column2 in the table

after deleted the both column, and ONLY changed to

protected $fillable = ['name', 'nick', ...etc];

i don't know my case is same as you, but all worked fine after the change

may be i suggest when u create the database table, all field must have a default value

rollerdead's avatar

Thanks @mushood i just read about you comment about changing column name to lowercase "id". Its solve my problem to updating my model

sbnc's avatar

I had the same issue. Digging into Laravel code using a debugger I've found binding were not done, so the update queries were executed with question marks instead of values. But the reason really was bad association. For example if a model A relates to model B, but you somehow associate a model type C, binding may fail, and SQL may also "fail" to raise an error. Just leaving it here for others looking for solutions: check that all related models (under the relations array) are of the correct type in the model being saved and all their related models as well. So what I mean is to verify runtime data, as from the source it might be hard to spot a typo or so which creates a wrong association.

Please or to participate in this conversation.