earmsby's avatar

Filament importer

I am banging my head trying to figure what the problem is with my importer.

I have a csv file like this:

"contract_description","default_copyright_holder","contract_type","date_executed"
"Contract 1","Subito Music Corp.","Publishing","11/14/18"
"Contract 2","Subito Music Corp.","Publishing","12/13/17"

The field "contract_type" is the name of a ContractType model so I have to find the id from the name supplied. I'm using the castStateUsing method like so:

ImportColumn::make('contract_type')
                ->castStateUsing(function (?string $state) {
                    Log::debug('Contract Type from CSV: ' . $state);
                    if (blank($state)) {
                        return null;
                    }
                    //query the ContractRights table to get the ID
                    $type = ContractType::where('contract_type_name', 'like', '%' . $state . '%')
                        ->first();
                    if (empty($type)) {
                        return null;
                    }
                    return $type->id;
                })
                ->requiredMapping()
                ->numeric()
                ->rules(['required', 'integer']),

As you can see I added a Log statement to try to troubleshoot why this kept failing. The log shows $state as 0. I've doublechecked that the values in the csv as the strings shown above but the $state is always zero. Why? I must be missing something dumb, but I just can't spot it.

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

It looks like your issue is because you’ve added the ->numeric() method, which tells Filament to cast the "contract_type" column to a number before your castStateUsing closure runs. That’s why $state is always 0—it gets converted before you get it. Just remove ->numeric(), and your closure will receive the actual string from the CSV.

Here’s the corrected code:

ImportColumn::make('contract_type')
    ->castStateUsing(function (?string $state) {
        Log::debug('Contract Type from CSV: ' . $state);
        if (blank($state)) {
            return null;
        }
        $type = ContractType::where('contract_type_name', 'like', '%' . $state . '%')
            ->first();
        if (empty($type)) {
            return null;
        }
        return $type->id;
    })
    ->requiredMapping()
    ->rules(['required', 'integer']);

Drop ->numeric(), and you should be golden!

Please or to participate in this conversation.