使用Laravel+league/csv导入TSV文件时遇Undefined array key 'titleType'错误
Let's break down what's going on here and fix that frustrating error step by step:
1. The #1 Culprit: Missing TSV Delimiter Configuration
Since you're working with a tab-separated (TSV) file, but the league/csv library defaults to comma-separated values. Without telling it to use tabs as the delimiter, it's probably reading your entire header row as a single key—meaning titleType doesn't actually exist in your record array.
Add this line right after creating the reader:
$reader->setDelimiter("\t");
2. Fix Operator Precedence in Your Condition
Your current if statement has a subtle bug with logic operator order. && runs before ||, so even if $record['titleType'] isn't set, the right side of the || will still try to access it, triggering the error.
Wrap your OR conditions in parentheses to ensure the isset check applies to both values:
if (isset($record['titleType']) && ($record['titleType'] === 'short' || $record['titleType'] === 'movie')) { // TODO }
3. Verify Your Header Names Match Exactly
Double-check that the header in your TSV file exactly matches titleType (no extra spaces, correct casing—capitalization matters!). Add a debug line before the loop to confirm what headers the library is actually reading:
// Print all detected headers to check for mismatches dd($records->getHeader());
This will reveal if there's a typo (like TitleType, title_type, or title type) that's causing the key to be missing.
Updated Working Code
Putting it all together, your code should look like this:
try { $reader = Reader::createFromPath(public_path() . '/data.tsv', 'r'); // Critical: Set delimiter for TSV files $reader->setDelimiter("\t"); $reader->setHeaderOffset(0); $records = Statement::create()->limit(1)->process($reader); // Uncomment to debug headers // dd($records->getHeader()); foreach ($records as $record) { // Fixed condition with proper precedence if (isset($record['titleType']) && ($record['titleType'] === 'short' || $record['titleType'] === 'movie')) { // TODO } } } catch (Exception $e) { echo $e->getMessage(), PHP_EOL; }
内容的提问来源于stack exchange,提问作者wellUKnow

