[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[Global exclusive service] Beyond's MSP in North America and China

[Global exclusive service] Beyond's MSP in North America and China

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

[For beginners] Laravel: I tried importing a CSV file!

Hello! This is Fukui from the System Development Department!
This time, I tried importing a CSV file using the Goodby CSV library in Laravel, so I would like to introduce it!
*This is my first blog post, so I'm really sweating as I write this...!

By the way, this time I worked on a Laravel project created under the Homestead environment.
The environment is as follows.
・PHP 7.4.5
・Laravel 7.14.1
・MySQL 5.7

table of contents

・Preparation
・Installing the Goodby CSV library
・Creating a CSV import method
・Operation confirmation
・Summary
・Bonus

Advance preparation

This time, I'm going to prepare a simple table that only registers the "title" and "price" of the book.

table name books
column id, title, price
[Column definition]

        Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->integer('price'); $ table->timestamps(); });

Here is the view I prepared.
view image
(Yes, it's simple! Sorry!)

After preparing the routing, CSV import method, and model, the next step is to install the Goodby CSV library.

Installing Goodby CSV library

Run the command below to install the Goodby CSV library.

composer require goodby/csv

Wait until it completes.
library installation

Once the installation is complete, follow the README on Goodby CSV's GitHub and add the following use declaration to the relevant controller.
Goodby CSV GitHub

use Goodby\CSV\Import\Standard\LexerConfig; use Goodby\CSV\Import\Standard\Lexer; use Goodby\CSV\Import\Standard\Interpreter;

Creating a CSV import method

The code for the CSV import part was written as follows.
Before the DB saving process, Goodby CSV config settings and Charset conversion are performed.

    public function importCsv(Request $request) { // Save CSV file $tmpName = mt_rand().".".$request->file('csv')->guessExtension(); //TMP file name $request-> file('csv')->move(public_path()."/csv/tmp",$tmpName); $tmpPath = public_path()."/csv/tmp/".$tmpName; //Goodby CSV config settings $config = new LexerConfig(); $interpreter = new Interpreter(); $lexer = new Lexer($config); //Convert Charset to UTF-8, ignore CSV header line $config->setToCharset("UTF -8"); $config->setFromCharset("sjis-win"); $config->setIgnoreHeaderLine(true); $dataList = []; // Assign a value to the $dataList array as a new Observer $interpreter-> addObserver(function (array $row) use (&$dataList){ // Get data for each column $dataList[] = $row; }); // Parse CSV data $lexer->parse($tmpPath, $ interpreter); // Delete TMP file unlink($tmpPath); // Registration process $count = 0; foreach($dataList as $row){ Book::insert(['title' => $row[0], ' price' => $row[1]]); $count++; } return redirect()->action('ItemsController@book')->with('flash_message', $count . 'You have registered a book! '); }

Operation confirmation

This time, I would like to save the following three lines of data as CSV. (I like music.)
CSV image

Select the CSV file, click upload, and
view image
the process appears to have been successfully completed and redirected.
Check the DB.
DB image

I was able to confirm that the data written in CSV was saved in the DB!

summary

I'm glad that I was able to successfully save the information written to CSV in the DB.
I was a little hesitant before starting work, but I found it very convenient as everything from installing the library to registering can be done in a relatively short time.
In reality, validation checks and exception handling are necessary, but I would like to use it depending on the situation, such as when I want to register a large amount of data.

bonus

■ Download CSV template file

By adding the following method, I was able to download the CSV template file.

    public function downloadCsv(): object { // Prepare output data $csvHeader = ["Title", "Price"]; // Set output data separated by commas $downloadData = implode(',', $csvHeader); / / Compatible with Excel $downloadData = mb_convert_encoding($downloadData, "SJIS", "UTF-8"); // Create a temporary csv file if (! file_exists(storage_path('csv'))) { $bool = mkdir( storage_path('csv')); // Throw an exception when directory creation fails if (! $bool) { throw new \Exception("Failed to create directory."); } } $name = 'book.csv' ; $pathToFile = storage_path('csv/' . $name); // Create CSV file if (! file_put_contents($pathToFile, $downloadData)) { throw new \Exception("Failed to write file.") ; } // Download response return response()->download($pathToFile, $name)->deleteFileAfterSend(true); }

■ Edit csv (VScode plugin)

I added this to take advantage of this work. It makes CSV very easy to view on VScode.
Edit csv

Edit csv Marketplace

lastly

I have opened the system development service site "SEKARAKU Lab" to which I belong.
Beyond is a one-stop service for everything from server design and construction to operation, so if you have any trouble with server-side development, please feel free to contact us.
SEKARAKU Lab: [https://sekarakulab.beyondjapan.com/](https://sekarakulab.beyondjapan.com/)

That's all for this time!
Thank you for reading to the end!

If you found this article helpful , please give it a like!
0
Loading...
0 votes, average: 0.00 / 10
16,485
X facebook Hatena Bookmark pocket
[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

The person who wrote this article

About the author

Hiroto Fukui

Joined Beyond in June 2020.
He works in the System Development Department (Yokohama office). His work focuses on PHP, developing game APIs and web systems, and developing Shopify private apps.
He likes music in general, mainly Western music, and plays the guitar as a hobby. His favorite TV shows are "Detective! Night Scoop" and "Infestation! Ad Street Heaven."