Laravel - efficient way to check database parameters before insert - php

I have populate a form of which every text field generated is based on the database result. I simply name every text field using the id. Now when the form is filled, I use controller to save it. But prior to insert the database, I loop the Request::input() to check every item whether such entry is exist or not. I just wonder if there is efficient way to check every item in the loop to insert it into db. Here is my code
public function store(Request $request, $id, $inid)
{
$startOfDay = Carbon::now()->startOfDay();
$endOfDay = Carbon::now()->endOfDay();
$instruments = InstrumentReading::whereBetween('created_at', [$startOfDay, $endOfDay])
->where('iv_inid', '=', $inid)
->get();
foreach ($request->input() as $k => $v) {
$read = new InstrumentReading;
$read->iv_inid = $inid;
$read->iv_ipid = $k;
$read->iv_usid = Auth::user()->id;
$read->iv_reading = $v;
$read->save();
}
if ($instruments->count() > 0) {
//to filter the iv_ipid...
foreach($instruments as $instrument)
{
$instrument->iv_status = "VOID";
$instrument->save();
}
}
}

In words of efficent approach what you can do is to simple check / fetch ONLY all posible rows from the database, and the check in the loop if the row was already inserted. Also fetch only iv_ipid column, as we do not need all columns from the table to do our check. It will be faster to select only the column we need. You can use directly Fluent (Query Builder) over Eloquent to pull the data from database as it greatly increase the performance for a simple query like this.
public function store(Request $request, $id, $inid)
{
// Search only records with submitted iv_ipid, iv_inid and created today
$alreadyInserted = DB::table('instrument_readings')
->whereBetween('created_at', [
Carbon::now()->startOfDay(),
Carbon::now()->endOfDay()
])
// Get only records with submitted iv_ipid
->whereIn('iv_ipid', array_keys($request->input()))
// Get records with given iv_inid only
->where('iv_inid', $inid)
// For our check we need only one column,
// no need to select all of them, it will be fast
->select('iv_ipid')
// Get the records from DB
->lists('iv_ipid');
foreach ($request->input() as $k => $v) {
// Very simple check if iv_ipid is not in the array
// it does not exists in the database
if (!in_array($k, $alreadyInserted)) {
$read = new InstrumentReading;
$read->iv_inid = $inid;
$read->iv_ipid = $k;
$read->iv_usid = Auth::user()->id;
$read->iv_reading = $v;
$read->save();
} else {
//todo
}
}
This is the most efficent way suggested until now, because you fetch at once only the records you are interested in, not all records from today. Also you fetch only one column, the one that we need for out check. Eloquent ususlally give a lot of overheat on the perfomance, so in the suggested code I use directly Fluent, which will boost the speed this part of code is executed by ~ 20%.
Your mistake in the original code is that you are doing database call each time in a loop. When you need such a simple task as a check, never put database calls, queries etc. in a loop. It is an overkill. Instead select all needed data before the loop and then do your checks.
Now this is in case you only need to save new records to database. In case you want to manipulate each record in the loop, let's say you need to loop through each submited entry, get get the model or create it if it does not exists and then do something else with this model, the most efficent way then will be this one:
public function store(Request $request, $id, $inid)
{
foreach ($request->input() as $k => $v) {
// Here you search for match with given attributes
// If object in DB with this attributes exists
// It will be returned, otherwise new one will be constructed
// But yet not saved in DB
$model = InstrumentReading::firstOrNew([
'iv_inid' => $inid,
'iv_ipid' => $k,
'iv_usid' => Auth::user()->id
]);
// Check if it is existing DB row or a new instance
if (!$model->exists()) {
// If it is a new one set $v and save
$model->iv_reading = $v;
$model->save();
}
// Do something with the model here
.....
}
This way Laravel will check if model with the passed parameters already exist in database, and if so it will return it for you. If it does not exist, it will create new instance of it, so you can then set the $v and save to db. So you are good to go to do anything else with this model and you can be sure it exists in database after this point.

First approach (efficiency first)
Consider using a simple SQL INSERT IGNORE Query and use Fluent, i.e.:
Make a composite unique key containing:
iv_inid
iv_ipid
created_time, up to an hour granularity, this is important, because created_at might have a far greater granularity than your intended purpose, and might slow things down a bit.
Use DB, i.e.:
DB::query(
"INSERT IGNORE INTO $yourTable VALUES ( ... )"
);
Pros:
- Extremely fast, all the necessary checking is done on the DB Server
Cons:
- You cannot know which values triggered a duplicate value / unique key violation, as related errors are treated as warnings.
Second approach (convenience first)
Use firstOrFail, i.e.:
$startOfDay = Carbon::now()->startOfDay();
$endOfDay = Carbon::now()->endOfDay();
// ... for
try {
InstrumentReading::where('iv_inid', $inid)
->where('iv_ipid', $k)
->whereBetween('created_at', [$startOfDay, $endOfDay])
->firstOrFail();
continue;
} catch (ModelNotFoundException $e) {
$instrumentReading = InstrumentReading::create([
// your values
]);
}
// ... endfor
Pros:
- Easy to implement
Cons:
- Somewhat slower than simple queries

Your code will send request to database every time you need to check the value. Instead, search all value of this day then check the value. This approach will send request to database only one time.
$startOfDay = Carbon::now()->startOfDay();
$endOfDay = Carbon::now()->endOfDay();
// Search only this day
$instruments = InstrumentReading::whereBetween('created_at', [$startOfDay, $endOfDay])->get();
foreach($instruments as $instrument)
{
// Check the value
}

Related

Improve performance of multiple row insertions in Laravel

I have a controller API method where I insert many rows (around 4000 - 8000), before inserting a new row I also check if a venue with the same ame was added already in the zone sothat's another Elouent call, my issue is I usually get timeout errors becuase the row inserting takes too much, I use set_time_limit(0) but this seems too hacky.
I think the key is the validation check I do before inserting a new row.
//Check if there is a venue with same name and in the same zone already added
$alreadyAdded = Venue::where('name', $venue['name'])->whereHas('address', function ($query) use ($address){
$query->where('provinceOrState' , $address['provinceOrState']);
})->orWhere('venueId',$venue['venueId'])->first();
Is there a way I can improve the performance of this method ? This is my complete method call:
public function uploadIntoDatabase(Request $request)
{
set_time_limit(0);
$count = 0;
foreach($request->input('venuesToUpload') as $index => $venue)
{
//Check if there is a venue with same name and in the same zone already added
$alreadyAdded = Venue::where('name', $venue['name'])->whereHas('address', function ($query) use ($address){
$query->where('provinceOrState' , $address['provinceOrState']);
})->orWhere('venueId',$venue['venueId'])->first();
if(!$alreadyAdded)
{
$newVenue = new Venue();
$newVenue->name = $venue['name'];
$newVenue->save();
$count++;
}
}
return response()->json([
'message' => $count.' new venues uploaded to database',
]);
}
use only one request to add the venues
$newVenues = [];
$count = 0;
foreach($request->input('venuesToUpload') as $index => $venue) {
//Check if there is a venue with same name and in the same zone already added
$alreadyAdded = Venue::where('name', $venue['name'])->whereHas('address', function ($query) use ($address){
$query->where('provinceOrState' , $address['provinceOrState']);
})->orWhere('venueId',$venue['venueId'])->count();
if(!$alreadyAdded) {
$newVenues [] = ['name' => $venur['name'];
}
}
if ($newVenues) {
$count = count($newVenues);
Venue::insert($newVenues);
}
As for the verification part, change the first to count cause you dont need to recover the data, just the information that it exists. And since you're verifying with both name and id, you can do some custom query that verifies all values in one query using a static table made from the request inputs and joining on the existing venues table where venues.id = null.

Laravel/Mysql - Manipulate large data

Dears,
Actually, I would like to know the best solution to manipulate BIG DATA in LARAVEL/MYSQL.
In my system, am uploading daily excel file (5K rows) into my DB, in case I find the same row in my table so I don't insert it, and if I find the same row, I changed the uploaded date in my DB.
Every time I upload the excel, am checking each row if exist in my table (table contain > 50K) with a normal array like the below
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->where('status', '=', $stat)
->where('bord_date', '=', $borddate)
->where('amount', '=', $row['amnt'])
->where('remarks', '=', $row['remarks'])
->exists();
if(!$res) {
// insert row ($table->save())
}
else {
//update uploaded date to this row.
}
this process takes lots of time bcz each time is checking the table. I tried to use array_chunk in order to insert, but still, the load is big (15 min to 20 min) to finish
Your advice are highly appreciated.
Thanks
You can create an hash of each row and store along with the row. Then check only the row with given hash.
For instance try this stub of code
foreach ($rows as $row) {
$hash = md5($row['phone'] . $row['draft_no'] . $row['due_date'] ...);
$res = Policiess::where('hash', $hash);
if (!$res) {
// create a new row and store the `$hash` in `hash` column
} else {
//update uploaded date to this row
}
}
if you not add new record same excel then not need check in database. but you add same excel file new record then insert all record after update this excel file
Why don't use laravel default eloquent method updateOrCreate.
Hope you already read about it if you don't you can read it from documentation other-creation-methods.
Let me explain what actually it does.
It Accepts an array of values and checks value is already in the database if it's already in the database it will update these values and also update column updated_at or if it's not already in the database, it will create a new entry in the table.
See eg below :-
policies::updateOrCreate(['value'=>1,'value'=>2,'so on...']);
and dont forget to add protected $fillable = [your column] , Because it's use $fillable for this.

How do I remove duplicate rows with same column values in Laravel?

I'm trying to make a artisan command in Laravel to remove all venues that have the same address and leave the one with the lowest ID number (so first created).
For this I need to check 3 fields: 'street', 'house_number', 'house_number_addition'
This is how far I've got:
$venues = Venue::select('street', 'house_number', 'house_number_addition', DB::raw('COUNT(*) as count'))
->groupBy('street', 'house_number', 'house_number_addition')
->having('count', '>', 1)
->get();
foreach ($venues as $venue) {
$this->comment("Removing venue: {$venue->street} {$venue->house_number} {$venue->house_number_addition}");
$venue->delete();
}
Only the delete is not working but is also not giving an error.
To be able to delete an item, Eloquent needs to know it's id. If you make sure your models' id is queried, you can call delete() without issues.
In your query, however, that won't work because you have a GROUP_BY statement, so SQL doesn't allow you to select the id column (see here).
The easiest solution here is to utilize Eloquent's Collection class to map over the models, something like:
$uniqueAddresses = [];
Venue::all()
->filter(function(Venue $venue) use (&$uniqueAddresses) {
$address = sprintf("%s.%s.%s",
$venue->street,
$venue->house_number,
$venue->house_number_addition);
if (in_array($address, $uniqueAddresses)) {
// address is a duplicate
return $venue;
}
$uniqueAddresses[] = $address;
})->map(function(Venue $venue) {
$venue->delete();
});
Or, to make your delete query a little more efficient (depending on how big your dataset is):
$uniqueAddresses = [];
$duplicates = [];
Venue::all()
->map(function(Venue $venue) use (&$uniqueAddresses, &$duplicates) {
$address = sprintf("%s.%s.%s",
$venue->street,
$venue->house_number,
$venue->house_number_addition);
if (in_array($address, $uniqueAddresses)) {
// address is a duplicate
$duplicates[] = $venue->id;
} else {
$uniqueAddresses[] = $address;
}
});
DB::table('venues')->whereIn('id', $duplicates)->delete();
Note: the last one will permanently delete your models; it doesn't work with Eloquent's SoftDeletes functionality.
You could, of course, also write a raw query to do all this.

Traversing through collection and updating records using Eloquent

I am using eloquent to pull a list of App\Post's from my database and deleting their file contents from my server.
I am traversing through the list and processing a delete action, on success I want to store a value to the respective App\Post but I am getting this error:
Method save does not exist.
Here is my code:
$posts_to_purge = Post::where('post_date', '<', \Carbon\Carbon::now()->subDays(7)->toDateString())->get();
if(count($posts_to_purge) > 0)
{
foreach ($posts_to_purge as $post) {
$directory = storage_path() . '/' . $post->post_date;
$deleted_folder = File::deleteDirectory($directory);
if($deleted_folder)
{
// 'purged' is a column in my Post table
$post->purged = 1;
}
else
{
Log::error('Unable to delete \''.$directory.'\' directory');
}
} // end foreach loop
// Update collection with purged posts
$posts_to_purge->save();
}
A side question to this... is this the most efficient way to do this? As I only want to update SOME records in the collection.. should I create a separate collection and save that only?
Collections don't have really have the power to interact with the database in Laravel. You are able to define a custom collection class with a save() method however there is a simple way to do what you want.
$posts_to_purge = Post::where('post_date', '<', \Carbon\Carbon::now()->subDays(7)->toDateString())->get();
if(count($posts_to_purge) > 0)
{
foreach ($posts_to_purge as $post) {
$directory = storage_path() . '/' . $post->post_date;
$deleted_folder = File::deleteDirectory($directory);
if($deleted_folder)
{
// 'purged' is a column in my Post table
$post->purged = 1;
$post->save ();
}
else
{
Log::error('Unable to delete \''.$directory.'\' directory');
}
} // end foreach loop
// Update collection with purged posts
$posts_to_purge->save();
}
Yes this does do one query per updated model, however updates by primary key are very fast.
If you were super committed to using one query, you could simply save each updated Post's ID to an array and do something like Post::whereIn ('id', $updated_ids)->update(['purged' => 1]);

Select MySQL If (ID) In Array

So I trying to build a notification system (CodeIgniter) and not store it in my database by this unique ID. Now I got some problem to using `SELECT query.
Also this is array stored in "value" row:
[{"id":0,"user_id":"1","comment":"That's a Nice Video.","posttime":1403523177,"status":1},{"id":1,"user_id":"4","comment":"Nice to see this..!!","posttime":1403590409,"status":1}]
And this is my (not work) query:
$query = $this->db->get_where('post_meta',array('status'=>1),in_array('user_id', $id));
Ideas?
Note: Notification will be sparated by "user_id".
You should not use in_array('user_id', $id) on that function because it returns boolean.
On the active record page: https://ellislab.com/codeigniter/user-guide/database/active_record.html you can take a look at parameter it takes for get_where() function
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Notice how the third parameter takes $limit which talks about the number of data you'll receive. (Leaving this blank will return you all data).
Some code examples:
If you just want to get the data with status = 1, use the following:
$query = $this->db->get_where('post_meta',array('status'=>1));
If you want to get the data with status = 1 and user_id = $id, use the following:
$this->db->like('value', '"user_id":"'.$id.'"');
$query = $this->db->get_where('post_meta',array('status'=>1));
The solution above is not the best, but it should work.
The $this->db->like() function will create rules to get data in value row which has "user_id":"$id" where $id is the value that you define.
What if I want to get all notifications and group them based on their ID?
I usually get all the data and then use PHP to group them into its own array. I think it's cheaper than relying on database to do that (Correct me if i'm wrong).
So use the first code:
$query = $this->db->get_where('post_meta',array('status'=>1));
Then iterate them using foreach() or whatever you find convenient.
$data = array();
foreach($query as $k=>$v) {
// Run a function to get User ID
$user_id = your_function_here($v->value);
if(!isset($data[$user_id]))
$data[$user_id] = array();
// This is just some example to group them together, you can optimize it to your own liking
array_push($data[$user_id],$v);
}
your_function_here() is your function to get the user_id from value row on your database.

Categories