Daniel L
Daniel L

Reputation: 263

Reading a .txt file and storing each line as a model

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!"?

Upvotes: 0

Views: 242

Answers (3)

Ksi
Ksi

Reputation: 177

$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());
    ]);
}

Upvotes: 2

jmvcollaborator
jmvcollaborator

Reputation: 2485

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
}

Upvotes: 0

Daniel L
Daniel L

Reputation: 263

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.

Upvotes: 0

Related Questions