phpjsonlaravel-4

JSON response assign to $var then save to db


I'm using Dropzone.js to upload multiple files in Laravel, which works fine uploads to my uploads folder but now I want the save the json object to the db.

Currently I have:

$file = Input::file('file');
$fileName = $file->getClientOriginalName();

$file->move(public_path().'/uploads/userfiles', $fileName);
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));

So now how would I store this in my users table in the uploads column?


Solution

  • Depends what you want to store...

    As I understand it, you want to associate uploads with a user? If you just want to store the filename, which may suffice, maybe do this:

    // models/User.php
    class User extends Eloquent {
    
        // ...
    
        public function setFilesAttribute(array $files)
        {
            $this->attributes['files'] = json_encode(array_values($files));
        }
    
        public function getFilesAttribute($files)
        {
            return $files ? json_decode($files, true) : array();
        }
    }
    
    // Your script
    $file = Input::file('file');
    $fileName = $file->getClientOriginalName();
    
    $file->move(public_path().'/uploads/userfiles', $fileName);
    $user = User::find(1); // Find your user
    $user->files[] = $fileName; // This may work, not too sure if it will being a magic method and all
    $user->files = array_merge($user->files, [$fileName]); // If not, this will work
    $user->save();
    
    return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));
    

    Something like this?

    Of course, you could get more complex and create a model which represents a "file" entity and assign multiple files to a usre:

    // models/File.php, should have `id`, `user_id`, `file_name`, `created_at`, `updated_at`
    class File extends Eloquent {
    
        protected $table = 'files';
    
        protected $fillable = ['file_name']; // Add more attributes
    
        public function user()
        {
            return $this->belongsTo('User');
        }
    }
    
    // models/User.php
    class User extends Eloquent {
    
        // ...
    
        public function files()
        {
            return $this->hasMany('File');
        }
    }
    
    // Your script
    $file = Input::file('file');
    $fileName = $file->getClientOriginalName();
    
    $file->move(public_path().'/uploads/userfiles', $fileName);
    $user = User::find(1); // Find your user
    $file = new File([
        'file_name' => $fileName,
        // Any other attributes you want, just make sure they're fillable in the file model
    ]);
    $file->save();
    $user->files()->attach($file);
    
    return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));