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

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

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

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.

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

How to reverse order of user name into last name first name and then orderBy name in laravel?

I have a name field in users table. I am storing full name in single field with first name first then last name.
What I want to do is to change the order to last name appearing first and then first name when I call $user->nameRev and orderBy the new name in laravel.
I already use $user->name in many places so cannot change that therefore I want $user->nameRev to reverse the name and use it in orderBy queries
How do I achieve this ?
I hope this can be help you.
Public function reversName()
{
$user = Auth::user();
$str = $user->name;
list($first, $last) = (explode(" ",$str));
$nameRev = $last. ''. $first;
$user->nameRev = $nameRev;
$user->save() ;
// Or
DB::table(users)->where('user_name')->insert($nameRev);
...
}

Store results of split function in variables

I have files in a directory like below:
first-file-name
2nd-file-name
3rd-file-name
.
.
n-file-name
I need to store each portion of file name in a separate variable because I want to insert these values in separate columns of table.
For this, I used the below script to get the each portion of a file name:
$var1=$item.BaseName.Split("-",3)[0]---------first
$var2=$item.BaseName.Split("-",3)[1]---------file
$var3=$item.BaseName.Split("-",3)[2]---------name
and can save these values in a variable. But the question is how can I do this for all files, if I use foreach loop then the variable values will be overwritten???
foreach(item in $items)
{
$var1=$item.BaseName.Split("-",3)[0]---------first
$var2=$item.BaseName.Split("-",3)[1]---------file
$var3=$item.BaseName.Split("-",3)[2]---------name
}
Here, in $items I got the file path using get-childitem.
I would create a PsCustomObject with the three parts:
$parts = $items | ForEach-Object {
[PsCustomObject]#{
FirstPart = $item.BaseName.Split("-",3)[0]
SecondPart = $item.BaseName.Split("-",3)[1]
ThirdPart = $item.BaseName.Split("-",3)[2]
}
}
now $parts is an array of these objects so you can access them using e. g.
$parts[0].FirstPart

Pasting serial numbers to existing entries from a forloop in laravel

I am trying to batch input a number of items, once they are in the database I want to add a unique suffix to the end of the item name. As an example:
[1]Item becomes Item-0001
[2]Item becomes Item-0002 etc....
I have this code at the moment:
$initial = Batches::orderBy('created_at', 'desc')->first();
$batch = Inventory::where('production_id', '=', $initial['batch'])->get();
$production_code = $initial['batch'];
for ($i=0; $i<($data['quantity']); $i++){
$index[]=$i;
}
$batch->each(function ($item, $index) use ($production_code) {
$item->update(['item' => $production_code . '-'.$index]);
});
This works and labels each of the items however it will only add it like so:
Item-0
Item-1
etc..
I would like to find a way to specify the suffix that is added and the starting number, in this case 0001.
Any help would be appreciated.
Thanks
Just add some leading Zeros:
sprintf('%04d', 1); // = 0001
sprintf('%04d', 113); // = 0113
Try to use sprintf() function:
sprintf("%'04d", $index);

Codeigniter Active Record return type

I tried to get a umat_id with this SQL query :
SELECT umat_id FROM msumat WHERE nama = $nama
I converted this SQL query into CI's Active Record :
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
So this query should return a string (example : "John").
But I got an error when I tried to echo it :
Object of class CI_DB_mysql_result could not be converted to string
I have tried something like this : echo (string)$terdaftar;, but it's not working.
All I want is to echo "John"
EDIT
Just said I want to insert "John" into a variable. How to do that?
$john = ????
As some of the users already pointed the solution, I'm only explaining why you did get this error so you can understand better the querying results that codeigniter gives.
This error:
But I got an error when I tried to echo it : Object of class
CI_DB_mysql_result could not be converted to string
Happens because you were trying to echo an object.
This piece of code
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
Will return an object, this object will have information about the query you've done.
With this object you can get the result(rows) as objects doing this:
$results = $terdaftar->result();
Or you if you feel more comfortable with arrays you can return the results(rows) as an array doing this:
$results = $terdaftar->result_array();
You can also get the number of results doing this:
$number_results = $terdaftar->num_rows()
And this is just an example you can read more about the results here
http://ellislab.com/codeigniter/user-guide/database/results.html
EDIT
A better explanation: imagine that we use the result_array() function to get the result in a pure array format:
$results = $terdaftar->result_array();
Now your variable $results is an array, to iterate through it and get the data you want you'll do something like this:
foreach ($results as $key => $row) {
//the row variable will have each row of your database returned by your query
//so if you want to access a field from that row,
//let's say for example the name field. You would do something like this
if($row['name']=='John')
echo $row['name'];
}
Try:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
foreach ($terdaftar->result() as $row)
{
echo $row->umat_id;
}
Read the documentation for more information.
Try this:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
$row = $terdaftar->row_array();
$your_variable = $row['umat_id']; /*Here comes your john*/

CodeIgniter - Returning multiple file upload details

Im using the codeigniter upload library to upload multiple files, which works fine ... What im having problems with is returning the information about the files.
Im using the following code to print the results for testing
echo '<pre>'; print_r($this->upload->data()); echo '</pre>';
A cut down version of the results are as follows
Array
(
[file_name] => Array
(
[0] => filename1.gif
[1] => filename2.jpg
)
)
The way my view is setup, is that i use jquery to insert multiple dynamic file input fields so the amount of files can be 1, it can be 50 and so on.
Im wondering how i would loop through that array to send each filename to the database
This would loop through the results and insert each into a table:
$data = $this->upload->data();
$table_name = 'files'; // change to whatever you need.
$column_name = 'file'; // change to whatever you need.
foreach ($data['file_name'] as $file_name){
$this->db->insert($table_name, array($column_name => $file_name));
}

Resources