Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laravel_newb's avatar

Inserting csv file content to a table

i am trying to develop a student information system and I wanted to register the student records in bulk. I have a excel sheet with student names and ids and want to insert these details directly into a table with a preset password so that students can directly login and change the information without having to register. So how can I insert contents of a csv into a table? Thanks

0 likes
2 replies
Indemnity83's avatar

Is this just a one time thing or something that might happen regularly?

If its one-time; then just use a DB tool like SequelPro to get the data in there.

If its a regular thing then there are lots of libraries for parsing CSV data, and even some built in php handling for crude imports.

The simplest example I can think of (untested), given you have a CSV in the following format

| name              | email                         | password |
|-------------------|-------------------------------|----------|
| Jigsaw            | [email protected] | password |
| Samara            | [email protected]           | password |
| Frederick Krueger | [email protected]      | password |

Then you could write a simple import script as follows

// in routes/web.php

Route::post('import', function(Request $request) {
    
    // Validate the data
    $this->validate($request, [
        'users' => 'required|file',
    ]);

    // Open up the CSV, and create an array of the data
    $file = $request->file('users');
    $csv = array_map('str_getcsv', file($file));
    
    // Pull out the first row as array keys
    array_walk($csv, function(&$a) use ($csv) {
        $a = array_combine($csv[0], $a);
    });
    array_shift($csv); # remove column header

    // Run through each record now and create a new user
    foreach( $csv as $user ) {
        Users::create($user);
    }
});

You should be able to merge the array_walk and foreach to save some of the code; but I wanted to make it clear what each step of the process was.

Again, this is untested code; there are likely some silly mistakes but the main point is to express a method of solving your problem.

1 like
laravel_newb's avatar

Thanks for the response. We have to upload annually as new students join. I tried your code and it worked.

Please or to participate in this conversation.