所以我完全不了解拉维尔,我正在try 一些东西.我想将一个CSV文件导入两个表中,我有一个名为lists的表,它将获得列表名和client_id.

Then I have a table called customers that will get name surname contact number as well as client_id and a list_id.

What I want to achieve is to import a CSV file that will take the file name and store it in the list table, then create an array through the CSV file and import the data into the customers table with the list and client id's.

我完成了第一部分,并且它正确地插入到Listers表中,现在如何从位于存储/文档中的CSV创建数组,然后将其插入到Customers表中?

namespace App\Http\Controllers;

use Input;
use DB;
use Illuminate\Http\Request;
use App\Http\Requests\ListsRequest;
use App\Lists;
use App\Clients;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ListsController extends Controller {

    public function index()
    {
        // $list_items = Lists::all();
        $clients = Clients::all();

        return view('lists.show', compact('clients'));
    }

    public function store(Requests\ListsRequest $request)
    {
        $input = $request->input();
        Lists::create($input);

        if (Input::hasFile('name'))
        {

            $file = Input::file('name');
            $name = time() . '-' . $file->getClientOriginalName();

            $path = storage_path('documents');

            $file->move($path, $name);

            // All works up to here
            // All I need now is to create an array
            // from the CSV and insert into the customers database
        }
    }
}

I chose to use the answer that I had accepted but I also played with the other answer and got it to work like this.

public function store(Requests\ListsRequest $request)
{
    $input = $request->input();
    $client_id = $request->input('client_id');

    if (Input::hasFile('name'))
    {
        $file = Input::file('name');
        $name = time() . '-' . $file->getClientOriginalName();
        $path = storage_path('documents');

        Lists::create(['client_id' => $client_id, 'name' => $name]);

        $reader = Reader::createFromPath($file->getRealPath());
        // Create a customer from each row in the CSV file
        $headers = array();

        foreach ($reader as $index => $row)
        {
            if ($index === 0)
            {
                $headers = $row;
            } else
            {
                $data = array_combine($headers, $row);
                Customers::create($data);
            }
        }

        $file->move($path, $name);

        return view('clients');
    }
}

推荐答案

There are 3 steps to read CSV file and import it in database in Laravel.

  1. 读取CSV文件
  2. 将其转换为数组
  3. Finally create records in our database.

Before we start, I have created a sample test.csv file and put it on my public folder under file folder:

name,email,password
user1,email1@email.com,pasxxxxxxxxxword
user2,email2@email.com,pasxxxxxxxxxword
user3,email3@email.com,pasxxxxxxxxxword

Step 1 and 2; I created a helper function called csvToArray, I just put it in my controller for now (this function is inspired from this link) it simply reads the CSV file and convert it to array:

function csvToArray($filename = '', $delimiter = ',')
{
    if (!file_exists($filename) || !is_readable($filename))
        return false;

    $header = null;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== false)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
        {
            if (!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }

    return $data;
}

第三步;这是我的最后一步,读取数组并将其插入数据库:

public function importCsv()
{
    $file = public_path('file/test.csv');

    $customerArr = $this->csvToArray($file);

    for ($i = 0; $i < count($customerArr); $i ++)
    {
        User::firstOrCreate($customerArr[$i]);
    }

    return 'Jobi done or what ever';    
}

Note: this solution assume that you have a model in your Laravel project and has the proper table in your database.

if you use dd($customerArr) you will get this
enter image description here

Laravel相关问答推荐

基于数据表 Laravel 4 导出 CSV 或 PDF

自定义 Laravel 关系?

如何在laravel中将数组转换为字符串?

Lumen和 MongoDB?

Laravel 5.4 存储:下载文件.文件不存在,但显然存在

如何修复无效请求(不支持的 SSL 请求)

Laravel 5.5 在迁移文件中设置整数字段的大小

在 Laravel Blade 中转义 vue.js 数据绑定语法?

Laravel Electron邮件验证模板位置

使用'with'时,Laravel belongsTo 返回 null

找不到列:1054字段列表中的未知列0-Laravel-我的代码中的任何地方都没有0列

如何使用外部图像生成 html div 的 screenshot截图?

如何在 Laravel 5.1 中为Electron邮件添加标题

如果值存在于另一个字段数组中,Laravel 验证规则

Laravel 模型:模型属性在哪里?

Laravel 邮件密件抄送

使用 Nginx 设置 Laravel

如何在 Laravel 中动态更改 .env 文件中的变量?

没有Access-Control-Allow-Origin标头 - Laravel

搜索结果分页 laravel 5.3