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

laracasts_asker's avatar

how to loop through Data posted through a cURL?

hi, a curl -d @data.csv http://myserver.com/gets routed to this function:

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    public function endpoint(Request $request)
    {
		$data = $request->getContent();
        \Log::info($data);
    }

and correctly shows the data from data.csv in the logs. But doing this:

    public function endpoint(Request $request)
    {
$data = $request->getContent();
while (($data) !== FALSE) {
$cafe = new Sheesh();
$cafe->colum1= $data[0];
$cafe->colum2 = $data[1];
$cafe->colum3 = $data[2];
$cafe->colum4 = $data[3];
$cafe->colum5 = $data[4];
$cafe->save();
}
    }

gives the following error:

production.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '8' for key 'data.PRIMARY' (SQL: insert into `data` (`colum1`, `colum2`, `colum3`, `colum4`) values (7, 9, 5, 2, 1)) {"exception":"[object] (Illuminate\Database\QueryException(code: 23000): 

79521 is the first data entry of data.csv. So how do I loop correctly through the data so I can insert them into a table like I tried? Thanks in advance!

0 likes
5 replies
koramit's avatar

You have to parse file content to array first.

$content = $request->getContent();
$items = explode(PHP_EOL, $content); // split content by new line
$items = array_map('str_getcsv', $items); // parse row to array

// I assume your csv has a head row so, make an associate array
array_walk($items, function (&$item) use ($items) {
  $item = array_combine($items[0], $item);
 });
 array_shift($items); // remove head row

foreach($items as $item) {
  $cafe = new Sheesh();
  $cafe->colum1 = $item['colum1'];
  ...
  $cafe->save();
}

Hope this help :)

1 like
laracasts_asker's avatar

thanks for the tip :). The problem is my csv is using delimter ; so I need to go like this:

$items = explode(PHP_EOL, $content); // split content by new line
$items = array_map(function($v){return str_getcsv($v, ";");}, $items); // parse row to array

But if I do this, I somehow only get the first line processed. Do you have tips how to overcome this? Is there a way to get the whole data.csv to open it with $handle = fopen("/opt/app-root/data/data.csv", "r");? Because going on from there would work for me.

koramit's avatar

I use this snippet for csv file on disk,

function loadCSV($path)
    {
        if (! file_exists($path)) {
            return [];
        }
        $items = array_map('str_getcsv', file($path));
        array_walk($items, function (&$item) use ($items) {
            $item = array_combine($items[0], $item);
        });
        array_shift($items);

        return $items;
    }
1 like
laracasts_asker's avatar

hi, my challenge is to actually get the file path. My linux server creates a file data.csv and now performes curl -d @data.csv http://laravelserver.com/ to post the file to my laravel server. The request gets routed succesfully to my controller with this route: Route::post('/', 'Controller@endpoint');

How can I now store data.csv so I can access it with $handle=fopen("/filepath/data.csv", "r");?

koramit's avatar

@laracasts_asker OK, now I think I understood,

curl -d so you post a file as data then you receive plain text content on endpoint without line separator so you can't explode content to lines.

// server post file as form (file remain a file and named it 'upload')
curl -F [email protected] http://around.test/file

// handle request
Route::post('/file', function () {
    if (! request()->file('upload')->isValid()) {
        return ['failed'];
    }

    $path = request()->upload->store('upload'); // file is store at storage/app/upload with random name

    $items = array_map('str_getcsv', file(storage_path('app/'.$path)));

    array_walk($items, function (&$item) use ($items) {
        $item = array_combine($items[0], $item);
    });
    array_shift($items);

    return $items[0]; // just test we get associative array
});

This works on my mac.

Hop this help :)

1 like

Please or to participate in this conversation.