Andrew Dikansky
Andrew Dikansky

Reputation: 21

Image upload from front-end

I'm trying to upload image-file from frontend in OctoberCMS

I have a model Person and relation:

public $attachOne = [
    'photo' => 'System\Models\File'
];

In php-block with upload form:

public function onUploadImage() {
    $person = Person::where('id', '=', $this->param('id'))->first();
    $person->photo = \Input::file('avatar');
    $person->save();
}

And my template:

<form method="POST" action="/persons/person/{{person.id}}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_handler" value="onUploadImage">
<input type="file" name="avatar" id="avatar" />

{{ form_token() }}
{{ form_sessionKey() }}

<button type="submit" data-attach-loading>Upload</button>

After submit it saves to DB only path 'http://my-site/storage/app/uploads/public/' and does not upload any files to filesystem. It seems like there are no some permissions, but I can easily upload images from backend.

Where is my error?

Upvotes: 0

Views: 656

Answers (2)

Andrew Dikansky
Andrew Dikansky

Reputation: 21

Here is the solution.

if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {

        $file = new System\Models\File;
        $file->data = Input::file('avatar');
        $file->is_public = true;
        $file->save();

        $person = Person::where('id', '=', $this->param('id'))->first();
        $person->photo()->add($file);
        $person->save();
    }

Upvotes: 0

Donkarnash
Donkarnash

Reputation: 12835

You must get the UploadedFile from the request and store it to one of the configured disks. And store the path to the image in the database.

Assume storage/app/public/images is the directory where the uploaded images should be stored.

public function onUploadImage() {

    if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {

        $file = request()->file('avatar');
        $filename = $file->getClientOriginalName();

        $person = Person::where('id', '=', $this->param('id'))->first();
        $person->photo = $file->storeAs('images', $filename)
        $person->save();
    }
}

Upvotes: 2

Related Questions