JSON响应分配给$ var然后保存到db

时间:2014-02-14 00:23:42

标签: json laravel-4

我正在使用Dropzone.js在Laravel中上传多个文件,这可以很好地上传到我的上传文件夹,但现在我想将json对象保存到db。

目前我有:

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

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

那么现在我如何将它存储在uploads列的users表中?

1 个答案:

答案 0 :(得分:1)

取决于您要存储的内容......

据我了解,您想将上传与用户关联起来吗?如果您只想存储文件名,这可能就足够了,可能会这样做:

// 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));

这样的东西?

当然,您可能会变得更复杂,并创建一个代表“文件”实体的模型,并将多个文件分配给一个用户:

// 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));