Pasting serial numbers to existing entries from a forloop in laravel - 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);

Related

Is there any way to explode a table inside query?

I have this table in my database.
ยป roles, and have content of 0,0,0,0,0,0
In this table i store user permissions. Example if he is an administrator it can be 0,0,0,0,0,1 or if he is an moderator and an administrator in the same time it can be 0,0,0,1,0,1.
But i don't know how i can show them in a query separated.
Example for administrator query only last parameter from that list 0,0,0,0,0,0.
So for it i have to do a explode in the query but i don't know how to do this.
I tried something like that to see if i can get the tables and explode it before query execute.
$query = User::where(
function($results) {
dd($results);
foreach($results as $result) {
print($result);
}
})->first();
Someone have an idea how i can do this?
if you have a fixed pattern you can "explode" it easily.
for example:
$result = "0,0,0,0,0,1"; // your data in for is string so:
$permission = explode(",",$result); // convert to an array.
// outpult is:
print ($permission);
[0 , 0 , 0 , 0 , 0 , 1 ];
print ($permission[5]);
// output is:
1
now you can access each cell of the array.
but It's not a clear way to make permission and role.
I suggest you use the different tables with different relationships.
I think this is not convenient way of implementing roles and permissions. If you are using Laravel then there is already a way to implement permissions in the form of gates and policies.
or you can implement it through a package like
Spatie Package
This might help it will return permissions ending with 1
User::where(function ($builder){
$builder->where('permission', 'regex','%1');
});
as a simple and appropriate solution,
you can also write your, where condition as below
->whereRaw("SUBSTRING_INDEX(SUBSTRING_INDEX(permission_column_name, ',', 6), ',', -1) = 1")
as you can see in the above code,
With SUBSTRING_INDEX(permission_column_name, ',', 6) function we will be able to extract everything up to the sixth value in your column separated by a comma.
Because SUBSTRING_INDEX() function also allows us to use negative values to extract fields counting from the right, we are using this ability to extract the rightmost field containing the last value of string with -1.
using the same above method you can also find any value available at any position as required in the given comma-separated string in a column.
Assuming that each user has a role, you can add some methods to the User model to handle permissions.
Class User extends Authenticatable {
private function getPermissions(): array {
return explode(',', $this->role)
}
public function isAdministrator(): bool {
$permissions = $this->getPermissions();
return $permissions[5] == 1;
}
public function isModerator(): bool {
$permissions = $this->getPermissions();
return $permissions[3] == 1;
}
}
Now you can use it in your code. Like this:
$user = auth()->user() // Or User::find($id) ...
if ($user->isAdministrator() || $user->isModerator()) {
// Do something
}

How to find difference of same column in foreach loop

I am take all field in for-each loop and take the difference of each two column
enter image description here
The above image 'tech_strt_km' is field name and take the difference of 122-22 and 200-122 how find these difference and store there values in another variyable i am using foreach loop for print these numbers
<?php
foreach($pexpn as $row) {
echo $row->tech_strt_km; ?><br>
} ?>
Any way to find the difference of same column
please help me !!
This should work fine. We add one to the current key to get the next value so we can subtract it from the current value, then we save these differences in an array diff for later usage.
$arr = array('22', '122', '200');
$diff = array();
foreach ($arr as $k => $v) {
if (!isset($arr[$k + 1])) {
// if we don't have a next item we are done
// break from foreach
break;
}
// abs only necessary if we expect negative differences and
// if we don't want that --- store differences in array
// for later usage
$diff[] = abs($arr[$k + 1] - $v);
}
print_r($diff);

String Format Get Attribute Function

I try to create an attribute function in a model which returns a string result but I would like to change the format of the string.
Actually I have a number licence (varchar column), which is displayed like 17923457 and I would like to change the format to 17-92-3457.
My function attribute actually is like:
public function getNumberAttribute() {
return $this->num_licence ;
}
Someone knows how I can display that specific format? Thanks a lot in advance
another one linear approach using vpsprintf
public function getNumberAttribute() {
return vsprintf('%d%d-%d%d-%d%d%d%d', str_split($this->num_licence));
}
for example :
$s = vsprintf('%d%d-%d%d-%d%d%d%d', str_split('17923457'));
print_r($s); // Outputs 17-92-3457
if you are sure you are always going to have 8 digits, you can do
public function getNumberAttribute() {
$first = substr($this->num_licence, 0, 2); //from position 0, take 2 digits
$second = substr($this->num_licence, 2, 2); //from position 2, take 2
$third = substr($this->num_licence, 4); //from 4 take the rest.
return $first . '-' . $second . '-' . $third;
}
You get it. Use substring to split your varchar/string. https://www.w3schools.com/php/func_string_substr.asp

Skip and take all?

In eloquent, how can I skip 10 rows and then get the rest of the table?
User::skip(10)->all();
The above does not work, but it gives you an idea what I am looking for.
Try this:
$count = User::count();
$skip = 10;
User::skip($skip)->take($count - $skip)->get();
With one query:
User::skip($skip)->take(18446744073709551615)->get();
It's ugly, but it's an example from official MySQL manual:
To retrieve all rows from a certain offset up to the end of the result
set, you can use some large number for the second parameter. This
statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
try something like this it work for sure..
$temp = User::count();
$count = $temp - 10;
$data = User::take($count)->skip(10)->get();
Laravel 5 returns Eloquent result as Collection.
So you can use collenction function slice();
$users = User::get();
$slicedUsers = $users->slice(10);

Laravel query optimization

I have a query in laravel:
...
$query = $model::group_by($model->table().'.'.$model::$key);
$selects = array(DB::raw($model->table().'.'.$model::$key));
...
$rows = $query->distinct()->get($selects);
this works fine and gives me the fields keys' that I need but the problem is that I need to get all the columns and not just the Key.
using this:
$selects = array(DB::raw($model->table().'.'.$model::$key), DB::raw($model->table().'.*'));
is not an option, cuz it's not working with PostgreSQL, so i used $rows to get the rest of columns:
for ($i = 0; $i<count($rows); $i++)
{
$rows[$i] = $model::find($rows[$i]->key);
}
but as you see this is it's so inefficient, so what can i do to make it faster and more efficient?
you can find the whole code here: https://gist.github.com/neo13/5390091
ps. I whould use join but I don't know how?
Just don't pass anything in to get() and it will return all the columns. Also the key is presumably unique in the table so I don't exactly understand why you need to do the group by.
$models = $model::group_by( $model->table() . '.'. $model::$key )->get();

Resources