xpromx's avatar

Best way to manage upload files in your database

Hello everyone,

I'm working in a new project and this project require to upload many files and associate this files with others entities. i always use this logic, i'm trying to improve my skills, asking to the community how usually make this part of the application, i want to make my code most clean possible.

I just want to show my way to do this and ask for opinions.

my table structure is:

Table: storage
- id
- user_id : integer
- file_name : string
- file_type : string
- file_caption : string
- model : string
- model_id : integer
- created_at
- updated_at

and i use this table to associate the files to my "Posts" or "Categories" or "Users"

then in my controller, for example Category:

public function update( Category $category, Request $request )
{
    $category->update( $request->all() );
    $category->storage( Input::file('picture') );

    return redirect()->route('admin_categories');
}

Categories Model:

public function storage( $file )
{
    if( !isset($file) ){ return false; }

    $storage = new AppStorage();
    return $storage->upload($file,  $this );
}

AppStorage , is in charge to upload the file and create the folder '/Y-m' to save the file there.

public function upload( $file, $model )
{
    $path = $this->makePath( $file );
    $content = file_get_contents($file->getRealPath());

    if( Storage::put( $path , $content ) )
    {
        // assign file_type, file_name, etc and save
        $this->save();

        return $this->id;
    }

    return false;
}
0 likes
0 replies

Please or to participate in this conversation.