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?
save
succeeded was true
.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('/'); }
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.
In short save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database, while in create method you are passing array, setting properties in model and persists in database in one shot.
Laravel Model::create or Model->save()$product = new Product(); $product->title = $request->title; $product->category = $request->category; $product->save();
save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.
Sometimes you might need to save multiple records at once and you can do so by using the "saveMany()" method or the "createMany()" method available to each of the Eloquent model relation. Do note that you need to have "hasMany()" relationship in order to do so.
Check your database table if the 'id' column is in uppercase 'ID'. Changing it to lower case allowed my save() method to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With