elieandraos's avatar

Change input value in eloquent model event (saved/saving)

hey,

consider i have a simple controller and model to handle news. (create/update/delete) where the news have a title and image.

i am trying to upload the image and remove them in the model event (i had the upload stuff in my controller but i think i keep it more simple in the news event model) everything went fine, until i faced a problem where i have to update the image url field in the db after either removing image (setting it back to null) or adding one (setting the filename)

i tried to run a simple model update() but it is going through an infinite loop, and i also tried the saving event instead of saved, and tried to update the input value inside the event methods, yet i faced the same issue.

any advice ?

/*****************
     * MODEL EVENTS  *
     *****************/

     public static function boot()
    {
        parent::boot();

        //delete image and thumbnails when deleting a news
        News::deleted(function($news)
        {   
            $news->removeImage();
        });

        //upload image on save (edit/create) and check the remove checkbox to delete image(on edit)
        News::saved(function($news){
            $input = Input::all();
            // if user checked the remove old image
            if(isset($input['remove_image']))
            {
                $news->removeImage();
                // update image field value in db to null ...
            }
            //upload new image
            if(isset($input['image']))
            {
                $uploaded_image = Input::file('image');
                $filename = $news->uploadImage($uploaded_image);
                // update image field value in db to filename ...
            }
        });
    }
0 likes
3 replies
pmall's avatar

Use the saving observer. This way you can upload the image and associate its name with the model before you save it to the db.

Plus it there is a problem with the file upload you can return false to cancel the model save.

elieandraos's avatar

@pmall yeah i was thinking of a pre-save event, observer might do it... i took a look at the docs, where should i register my observer class ? start/global.php ?

pmall's avatar

You can do it I your boot method like your example. Just change News::saved to News::saving.

Please or to participate in this conversation.