mercredi 17 mars 2021

Randomly Generate 4 digit Code & Check if exist, Then re-generate

My code randomly generates a 4 or 5 digit code along with 3 digit pre-defined text and checks in database, If it is already exists, then it regenerates the code and saves into database.

But sometimes the queries get stuck & become slower, if each pre-defined keyword has around 1000 record.

Lets take an example for one Keyword "XYZ" and Deal ID = 100 and lets say it has 8000 records in database. The do while loops take a lot of time.

$keyword = "XYZ"; // It is unique for each deal id.
dealID = 100; // It is Foreign key of another table.
$initialLimit = 1;
$maxLimit = 9999;

do {
    $randomNo = rand($initialLimit, $maxLimit);
    $coupon = $keyword . str_pad($randomNo, 4, '0', STR_PAD_LEFT);

    $findRecord = DB::table('codes')
        ->where('code', $coupon)
        ->where('deal_id', $dealID)
        ->exists();

    } while ($findRecord == 1);

As soon as the do-while loops end, Record is being inserted into database after above code. But the Above code takes too much time,

The above query is printed as follow in MySQL. like for above example deal id, it has already over 8000 records. The above code keeps querying until it finds. When traffic is high, app becomes slower.

select exists(select * from `codes` where `code` = 'XYZ1952' and `deal_id` = '100');
select exists(select * from `codes` where `code` = 'XYZ2562' and `deal_id` = '100');
select exists(select * from `codes` where `code` = 'XYZ7159' and `deal_id` = '100');

Multiple queries like this get stuck in database. The codes table has around 500,000 records against multiple deal ids. But Each deal id has around less than 10,000 records, only few has more than 10,000.

Any suggestions, How can I improve the above code?

Or I should use the MAX() function and find the code and do the +1 and insert into db?



via Chebli Mohamed

Query buider Laravel

I have a table to store my articles. I have no pictures in this table, and my photos are in another table. I have added 5 posts and each post has 3 pictures. Now I want to get 5 posts and each post only takes 1 out of 3 pictures of it, how to do ?? i need help, thanks

enter image description here

enter image description here



via Chebli Mohamed

mardi 16 mars 2021

PDF file is not opening on some computers which is created by laravel?

We are creating pdf file whith hepl of laravel This file is opening on majority of laptops and software but not opening in few computers. can't figure out the reason. this is the error they are getting

enter image description here

Code I am using to creating pdf file

 $apiInstance = resolve(\XeroAPI\XeroPHP\Api\AccountingApi::class);
        $result = $apiInstance->getInvoiceAsPdf($this->xeroCredentials->getTenantId(), $invoice->xero_invoice_id, "application/pdf");

        $content = $result->fread($result->getSize());

        Storage::disk('s3')->put(getSettingValue('s3_invoice_pdfs') .$invoice->xero_invoice_number.'.pdf', $content, 'public');


via Chebli Mohamed

Laravel 5.5 Queue Job doesn't respect timeout

I have a job in Laravel 5.5 that doesn't respect the value in the variable public $timeout set on the job as described in the laravel documentation.

If I set the value of $timeout to, for example, 120 seconds I would expect the job to be terminated after it has ran for 120 seconds. I'm using RabbitMQ on a Heroku dyno.

Codebase: Laravel 5.5

Extension: RabbitMQ Queue driver for Laravel

Platform: Heroku dyno (Amazon).

Example code:

class ExampleJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 120;

    public function handle()
    {
        DB::statement($this->buildCallStatement());
    }
}

Example Procfile:

worker: php artisan queue:listen rabbitmq --queue=high,medium,low --tries=1 --memory=512 --timeout=0


via Chebli Mohamed

My laravel form is not submitting. What can I do? Please help me and Thank you in advance

Name of my controller is CustomerController. This is my controller. There are 5 fillable field out of which 1 is image.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'category' => 'required',
        'mobile_number_1' => 'required|min:10|max:10',
        'mobile_number_2' => 'min:10|max:10',
        'aadhar_card' => 'required',
    ]);
    $aadhar_card = $request->file('aadhar_card');
    $new_name = rand() . '.' . $aadhar_card->getClientOriginalExtension();
    $aadhar_card->move(public_path('aadhar_card'), $new_name);
    $form_data = array(
        'aadhar_card' => $new_name,
    );
    Customer::create($form_data);
    $customer = Customer::create([
        'name' => $request->input('name'),
        'category' => $request->input('category'),
        'mobile_number_1' => $request->input('mobile_number_1'),
        'mobile_number_2' => $request->input('mobile_number_2'),
    ]);

    return redirect('customers.index')->with('success', 'Data added successfully.');
}

This is my create form. There are 5 fillable field 1. name ,2. mobile number 1 ,3. mobile number 2 ,Category and aadhar card.

<form method="post" action="" enctype="multipart/form-data">
        @csrf
        <table>
            <tr>
                <td>Name :</td>
                <td><input type="text" name="name" class="form-control" placeholder="Name"></td>
            </tr>
            <tr>
                <td>Category :</td>
                <td>
                    <select name="category" id="category">
                        <option value="Painter">Painter</option>
                        <option value="Contractor">Contractor</option>
                        <option value="Carpenter">Carpenter</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Mobile Number 1 :</td>
                <td><input type="text" name="mobile_nubmer_1" class="form-control" placeholder="Mobile Number"></td>
            </tr>
            <tr>
                <td>Mobile Number 2 :</td>
                <td><input type="text" name="mobile_nubmer_2" class="form-control" placeholder="Mobile Number ( Optional )"></td>
            </tr>
            <tr>
                <td>Aadhar Card :</td>
                <td><input type="file" name="aadhar_card" class="form-control"></td>
            </tr>
            <tr><button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button></tr>
        </table>
    </form>


via Chebli Mohamed

get the required data from table

I have the table with fields id,before_value,after_value.I have the array value for parent_id ('11')

I want to get the value in below constraints

  1. before value is OIN and after value is MGL
  2. after value is MGL and before value is not OIN and parent id is in my array ('11','18');

3 before value is MGL and after value is MQL

enter image description here

I have tried as

$audit_table_result=$audit_table_result->orWhere(function ($query) use ($meeting_ids){
            return $query->where('after_value_string','=','MGL')->whereNotIn('before_value_string',['OIB'])->whereIn('parent_id',['11','18']);
             })->orWhere(function ($query) {
            return $query->where('before_value_string','=','MGL')
           ->where('after_value_string','=','MQL');
             })->orWhere(function ($query) {
            return $query->where('before_value_string','=','OIB')
           ->where('after_value_string','=','MGL');
             })->where('parent_id',$added_id)   
            ->get();

I expected to get the id 1,3,4,5 but I'm getting 1,2,3,4,5,6



via Chebli Mohamed

How in laravel with stripe-php get balance after payment?

In laravel 5.8 app with stripe/stripe-php: ^7.50 when customer pays fir provided services it has code:

    \Stripe\Stripe::setApiKey( config('app.STRIPE_TEST_KEY') );
    $user = User::where('id', $request->user_id)->first();
    $customer_id = $user->stripe_customer_id;

    $charge = \Stripe\Charge::create([
        'amount' => $request->amount * 100, // Say $request->amount= 50
        'currency' => $request->currency,   // USD
        'customer' => $customer_id
    ]);
    TransactionsTable::create([
        'user_id' => $user->id,
        'type' => $request->card['brand'],
        'amount' => $request->amount,
        'currency' => $request->currency,
        'transaction_id' => $charge->id,
        'status' => $charge->status
    ]);

And USD 50 is subtracted from customer card and is added to the owner of stripe account (in dev app.STRIPE_TEST_KEY) My questions 1) as I want to send email to owner of stripe account in which way can I get balance of his after successfull operation? How ths sum is differ under test/live?

  1. How can I check error in case of invalid operation? Say if customers card has no enough money or expired? In catch block with $e->getMessage() or are there some better way?

Thanks!



via Chebli Mohamed