Luka's avatar
Level 1

On update, Check if Column changed before save()

I have an update form for a Post. I use a Wysiwyg Editor for the Post Body where I can also add images. I was now wondering how I would handle the Update, since I save the tag in the Post Body and upload my images to a folder.

I thought about the option to delete all the images and pull them in again, no matter if the Post Body changed or not or do that only, if something in the Post Body changed. I thought the second option would be better so I looked around if I can actually compare if the field has changed. I came across isDirty() so I tried below, but even if I dont touch it and only change the title, I run into it. If I var_dump it I get a true every time. I must misunderstand the use of it, is there a way to check it or should I just delete it all or is there a better way?

  $post = Post::findOrFail($id);
  $post->body = $request->input('body');
  if($post->isDirty('body')){
    // body has changed
0 likes
6 replies
Snapey's avatar

Why not compare them directly?

if($post->body == $request->input('body')) {
1 like
jlrdw's avatar

Or if record is just being updated, as long as the updated field passes validation, why even need a compare.

Billy Ray

now edited to be

Billy Bob

If Billy Bob is valid for the field you are good to go.

newbie360's avatar

if i get your meaning correct, look like this ? idk

$newBody = 'Hello world [img]aaa.jpg[/img], this is a test [img]bbb.jpg[/img]';
$savedImages = ['aaa.jpg', 'bbb.jpg', 'ccc.jpg'];

foreach ($savedImages as $image)
{
    if (! str_contains($newBody, '[img]' . $image . '[/img]'))
    {
        // delete the image
    }
}
Luka's avatar
Level 1

@ Snapey I tried it but it always shows up as different, even if I have not touched the content.

For example: That is what is being send

 <p><img class="img-fluid" src="/storage/uploads/posts/5b6b68ce795cb/15337658380.png">test</p>

And that is what is in the database, but when I compare it shows that it is different.

 <p><img class="img-fluid" src="/storage/uploads/posts/5b6b68ce795cb/15337658380.png">test</p>

@jlrdw the reason I don't just want to update everything is that I read out the posted body and check for any images inside it. I then create a filename and a foldername and upload the files to the folder I create dynamically. The first image name in the post gets then added to the db to be used as the default image. If nothing changed on the Post Body, then I could really save this step.

Please or to participate in this conversation.