String Format Get Attribute Function - laravel

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

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
}

A non well formed numeric value encountered After Formatted by number_format() function

I am using Accessor for format my number value. Problem start when i try to calculate the formatted value because number_format() function return a string value. Is there any alternative way to format the number value and calculate the value also.
class Order extends Model
{
protected $fillable = ['order_quantity'];
public function getOrderQuantityAttribute($value)
{
return number_format($value);
}
}
Error shown when i try to calculate like,
$order->order_quantity * 100;
//$order->order_quantity value is 10,000
may be this will help you. using str_replace remove comma from string.
$newOrderQuantity = str_replace(',', '', $order->order_quantity); // converting to "10000"
so on, you can use (int)$newOrderQuantity for calculation.
just replace ',' with '' :
str_replace(',','',$order->order_quantity) *10

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);

Laravel 5 - how to get a random row from first 30 records in eloquent?

I am trying to get a random row from the top 30 records in a table. I sort all the records by score first, and take 30 records in a scope of the eloquent model:
public function scopePopular($query, $d)
{
return $query->where('d', $d)->orderBy('score', 'desc')->take(30);
}
Then in a class:
$cnt = Record::popular($d)->count();
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first();
return $record;
But when I check in php artisan tinker, I found that Record::popular($d)->count(); will return all the records number instead of 30. How can I correct this problem? Thanks.
Use get() before count() to run the query before count:
$cnt = Record::popular($d)->get()->count();
You are running the query 2 times. That is not necessary.
$cnt = Record::popular($d)->count(); // First query
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first(); // Second query
return $record;
Instead you can do it like this:
return Record::popular($d)->get()->random(); // One query only

Make unique invoice numbers with mysql and use

At the moment this is my function to create a random unique invoice number which is stored in a form's hidden field
function generate_invoice_number() {
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'];
$nr = 501 + $nr_last;
$value = sprintf( '%04d', $nr );
$number = 'LEDEXPO'.date('Y').'-'.uniqid().'-'.$value;
return $number;
}
I have a problem when multiple people are using the form at the same time, say 3 people are using the form they all have the same number generate.
So i added uniqid(), so $value could be duplicated but $number should be unique? Is this correct or is there a better way?
How can i make test function to test this function on uniqueness?
regards
Try This:
function generate_invoice_number()
{
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'] + 1;
$number = date('Ymd') . $nr_last;
return $number;
}

Resources