php - 如何将图像上传到具有多对多关系的表单?

标签 php mysql laravel-5

这与 this question 非常相似.我正在使用 Laravel 5 并尝试使用表单将文件(图像)添加到我的数据库中。我有一个表单可以将各种数据(标题、描述、图像)添加到我的文章类中。一篇文章也属于“belongsToMany”类别和日期(多对多 r/ship)。下面的代码允许我上传我的数据,但是它添加了文章的三个实例!前两个实例具有正确的照片路径/名称 (photo.jpg)。第三个实例将这样的名称添加到数据库:/tmp/phphJIIY1。它正确地将 id 添加到数据透视表。

我认为是'store'函数的这一行

        $article = Article::create($request->all());    

这是导致问题的原因,但我需要该行,否则我会收到 my last question 中描述的错误.

我如何订购/更改此代码以便我可以上传图像向我的文章添加类别/日期?我已经安装了 intervention\image 但我还没有使用它。

   public function create()
{

    $categories = Category::lists('name', 'id');
    $days = Day::lists('dayname', 'id');
    return view('articles.create', compact('categories', 'days'));
}

public function store(ArticleRequest $request)
{

   $image_name = $request->file('image')->getClientOriginalName();
   $request->file('image')->move(base_path().'/public/images', $image_name);
   $article = ($request->except(['image']));
   $article['image'] = $image_name;
   Article::create($article);

//在这条线之上它自己可以正常工作(如果我在下面注释掉它就可以正常工作但我需要我的多对多 r/ship 才能工作)

    $article = Article::create($request->all());

//必须在上面添加这一行才能使“categories()”工作。

    $categoriesId = $request->input('categoryList');
    $article->categories()->attach($categoriesId);
    $daysId = $request->input('dayList');
    $article->days()->attach($daysId);
    return redirect()->route('articles_path');

}

最佳答案

对不起,我误会了。我是新手,也在尝试解决问题。 我有同样的问题,正在保存 2 个候选记录,我这样做是为了让它工作:

    $file = Request::file('resume');
    $extension = $file->getClientOriginalExtension();
    Storage::disk('local')->put($file->getFilename().'.'.$extension,  File::get($file));
    $resume = new Resume();
    $resume->mime = $file->getClientMimeType();
    $resume->filename = $file->getFilename().'.'.$extension;
    //save resume & put candidate's id as foreign key
    $candidate=new Candidate();
    $data=array_except($data, array('_token','resume'));
    //attach blank candidate to current user
    $user->candidate()->save($candidate);
    $candidate->resume()->save($resume);

    //find the right instance of candidate we want to update*
    $candidate=$user->candidate($user);
    //Now update the candidate with data once it's been attached.
    $candidate->update($data);

关于php - 如何将图像上传到具有多对多关系的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33382760/

相关文章:

PHP获取目录的创建时间

php - 这个查询有什么问题?为什么本地结果不同?

php - 在共享主机中仅使用 FTP 部署 Laravel 5

php - 从基础中选择时间作为 UNIX_TIMESTAMP(time) laravel 5

php - Laravel 5.1 单页多表单命名消息包

php - 如何在网络服务器中执行 CUDA 文件 (PHP)

当选择区域时,PHP 从数据库填充数据

php - 未捕获的语法错误 : Unexpected token ILLEGAL

php - 内连接包含 3 个表的计数

mysql - Ruby 变量返回 [["variable"]]