简体   繁体   English

使用Laravel 5.5上传多张照片并存储在数据库中

[英]Uploading multiple photos and storing in the database with Laravel 5.5

I've been following a tutorial here on how to attach multiple files to a Laravel Item but I keep running into an error with the saving of the files to the table. 我一直在这里关注如何将多个文件附加到Laravel项目的教程,但是在将文件保存到表中时一直遇到错误。

Call to a member function store() on array

The Job saves perfectly fine to my database but that error happens to my attempt at saving the files. 作业可以很好地保存到我的数据库,但是该错误发生在我尝试保存文件时。

I seem to be getting this error any time I try to use the store method on files and I'd love any insight into this. 每当尝试在文件上使用存储方法时,我似乎都会遇到此错误,并且我希望对此有所了解。

JobController.php JobController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

use App\Job;
Use App\Brand;
Use App\JobType;
use App\JobFile;

class JobController extends Controller
{
    ...

    public function store(Request $request)
    {
        ...

        $job = Job::create([
            'title' => $request->title,
            'brand_id' => $request->brand_id,
            'job_type_id' => $request->job_type_id
        ]);

        foreach ($request->files as $file) {
            $filename = $file->store('job-files');
            JobFile::create([
                'job_id' => $job->id,
                'filename' => $filename
            ]);
        }

        return redirect('/jobs');
    }
}

create.blade.php create.blade.php

<form action="/jobs/create" method="POST" enctype='multipart/form-data'>
    ...
    <div class="form-group">
        <label for="file">File Upload(s)</label>
        <input type="file" name="files[]" multiple>
    </div>
    ...
</form>

You must get first the array of all files after than you can make the foreach. 您必须先获取所有文件的数组,然后才能进行foreach。

if($request->hasFile('files')) {
    $files = $request->file('files');
    foreach ($files as $file) {
        $filename = $file->store('job-files');
        JobFile::create([
            'job_id'   => $job->id,
            'filename' => $filename
        ]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM