Home > Software design >  Reading a .txt file and storing each line as a model
Reading a .txt file and storing each line as a model

Time:08-21

I have a .txt file that has names:

john doe
mary roe
...
...

I've a model Person which has the following $fillable:

protected $fillable = [
        'list_id',
        'name'
    ];

I'm trying to populate a specific List with the names from this specific file, but I'm sort of stuck trying to understand how to properly do this. I'm looking mostly to seed the database with a series of lists and names on each one (coming from a .txt file each list).

What would be the most convinient way to read the file and tell Laravel "Hey, store each line under (lets say) list 1!"?

CodePudding user response:

$file = new \SplFileObject(‘/path/to/your/file.txt’);

$list = List::where(…)->first(); // find the list matching your file 

while (!$file->eof()) {
    // assuming you have List::people() hasMany relation:
    $list->people()->create([
        ’name’ => trim($file->fgets()); // you can format, trim, sanitize your line here
    ]);
    // Without relation:
    Person::create([
        ’list_id’ => $list->id,
        ‘name’ => trim($file->fgets());
    ]);
}

CodePudding user response:

the solution would be:

$file = new \SplFileObject("file.txt");
while (!$file->eof()) {
            // Echo one line from the file.
            $echo $file->fgets();
        }
$file = null;

Hope this helps someone out there.

CodePudding user response:

Hi SplFileObject is a neat way and object oriented, further info: SplFileObject

$myFile = new SplFileObject("data.txt");

while (!$myFile->eof()) {
    echo $myFile->fgets() . PHP_EOL; //line N
//Here you can pass list id and the value retrieved above and store it on the DB
}
  • Related