mercredi 12 mai 2021

How to detect update event in model in Laravel 8

Good day to all The situation is as follows In the controller, in the update method, I try to update the object There is an image in the fields of this object Wrote a trait to process this field and load an image In the model itself, I called the update method, which just determines the event of updating the object The problem lies in the following image in the specified directory is loaded and the entry itself in the database does not change Here is my code

  1. Controller
  2. Model
  3. Trait

There is extra code in the model

public function update(Request $request, MainHeader $mainHeader): RedirectResponse
    {
        $mainHeader->update([
            'language_id' => $request->language_id,
            'brandLogoImage' => $request->file('brandLogoImage'),
            'homeTitle' => $request->homeTitle,
            'ourProjectsTitle' => $request->ourProjectsTitle,
            'contactTitle' => $request->contactTitle,
            'feedbackTitle' => $request->feedbackTitle,
        ]);
        return redirect()->route('admin.header.index')->with('success', 'Данные успешно обновлены');
    }
public function setBrandLogoImageAttribute($value): string
    {
        return $this->uploadImage('brandLogoImage', $value);
    }

    public function update(array $attributes = [], array $options = [])
    {
        $this->uploadImage('brandLogoImage', $attributes['brandLogoImage']);
        $this->setBrandLogoImageAttribute($attributes['brandLogoImage']);
        return parent::update($attributes, $options); // TODO: Change the autogenerated stub
    }
protected function uploadImage(string $attr, $value): string
    {
        $uploadDir = public_path('uploads/');
        $imageDir = public_path('uploads/image/');
        if (!file_exists($uploadDir)){
            mkdir($uploadDir);
        }
        if (!file_exists($imageDir)){
            mkdir($imageDir);
        }
        if (!file_exists(public_path("uploads/image/$this->table/"))){
            mkdir(public_path("uploads/image/$this->table/"));
        }
        $imageName = Str::random(12) . '.png';
        Image::make($value)->save(public_path("uploads/image/$this->table/$imageName") , 100);
        return $this->attributes[$attr] = (string) "uploads/image/$this->table/$imageName";
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire