Skip to content

Instantly share code, notes, and snippets.

@junaidulqayyumqureshi
Created April 14, 2020 06:00
Show Gist options
  • Save junaidulqayyumqureshi/1f5a1fca2c7db1957d5bd70c20c66e6a to your computer and use it in GitHub Desktop.
Save junaidulqayyumqureshi/1f5a1fca2c7db1957d5bd70c20c66e6a to your computer and use it in GitHub Desktop.
Code snippets which I use more often in projects
@junaidulqayyumqureshi
Copy link
Author

junaidulqayyumqureshi commented May 7, 2020

Laravel Backup

Choose version first from
Source

For laravel v5
composer require "spatie/laravel-backup:^5.0.0"

For Laravel v6
composer require spatie/laravel-backup

For config files
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

For backup
php artisan backup:run
OR
php artisan backup:run --only-db

Email Backup

Source

Non-Spatie Backup

Copy following content in a app > Console > Commands > DBBackup.php

<?php
namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;

class DBBackup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:backup';
/**
 * The console command description.
 *
 * @var string
 */
    protected $description = 'Create Database Backup';
/**
 * Create a new command instance.
 *
 * @return void
 */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $filename = "backup-" . Carbon::now()->format('Y-m-d') . ".gz";
        $command = "mysqldump --user=" . env('DB_USERNAME') . " --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . "  | gzip > " . storage_path() . "/app/backup/" . $filename;
        $returnVar = null;
        $output = null;
        exec($command, $output, $returnVar);
    }
}

Run php artisan db:backup

@junaidulqayyumqureshi
Copy link
Author

PHP Script Execution Time

$time_start = microtime(true); 
//sample script
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

@junaidulqayyumqureshi
Copy link
Author

Last DAY PHP => Previous Day PHP

date('Y-m-d', strtotime('-1 day', strtotime("2020-01-01")))

@junaidulqayyumqureshi
Copy link
Author

Clone array but without reference JS

arr2 = JSON.parse(JSON.stringify(arr1))

@junaidulqayyumqureshi
Copy link
Author

Loop through a JSON Object Keys

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

@junaidulqayyumqureshi
Copy link
Author

Check storage of a directory

sudo du -sh /var

@junaidulqayyumqureshi
Copy link
Author

Image Magic OR Imagick

Source

@junaidulqayyumqureshi
Copy link
Author

INSERT INTO SELECT STATEMENT

INSERT into tableA (id, colA, colB, ...) (SELECT id, colA, colB, ...)

@junaidulqayyumqureshi
Copy link
Author

ZIP Archive Linux

zip -r myfiles.zip mydir

@junaidulqayyumqureshi
Copy link
Author

Bubble Sort

$arr = [7,3,1,4,2];
$toGo = true;
while($toGo){
    $swap = false;
    for ($i=0; $i < sizeof($arr); $i++) { 
        if($i == sizeof($arr)-1)
            continue;
        if($arr[$i] > $arr[$i+1]){
            $swap = true;
            [$arr[$i], $arr[$i+1]] = [$arr[$i+1], $arr[$i]];
        }
    }
    if(!$swap)
        $toGo = false;
}
echo "<pre>"; print_r($arr);

@junaidulqayyumqureshi
Copy link
Author

PHP ARRAY FUNCTIONS (Fat Arrow)

array_map(fn($tag) => new Tag($tag), $tags)
array_filter($stock, fn($item) => $item['qty'] > 0)
array_reduce($team, fn($carry, $person) => $carry + $person['points'], 0);

@junaidulqayyumqureshi
Copy link
Author

Laravel Service Containers

Source
image

For example:
You have a class App\Billing\Stripe which requires some additional values in it's constructor i.e. Secret Key

Now you can bind App with the class and inject the dependency in it's constructor like it is done in the Screenshot above.

You won't need to reinitialize the class ever again in the project as you have already done this and now you can call the binding by App::make('classname') or resolve('classname') and you will have the ready instance without passing anything in the constructor

@junaidulqayyumqureshi
Copy link
Author

MYSQL STORE PRODCEDURE

DELIMITER $$
CREATE PROCEDURE `insert_into_order_contents_tables`(
    IN `pref_id` INT,
    IN `item_quantity_booker` VARCHAR(100)
)
BEGIN
    insert into order_contents (
        pref_id,
        item_quantity_booker
    ) values (
        pref_id,
        item_quantity_booker
    );
END$$
DELIMITER ;

@junaidulqayyumqureshi
Copy link
Author

POSTGRESQL DB Export Windows Command Line


Open Powershell.
Go to Postgres bin folder. For example: cd "C:\Program Files\PostgreSQL\9.6\bin"
Enter the command to dump your database. For example: ./pg_dump.exe -U postgres -d my_database_name -f D:\Backup\<backup-file-name>.sql.
Type password for your postgres user.

@junaidulqayyumqureshi
Copy link
Author

CORS ISSUE

The CORS issue should be fixed in the backend. Temporary workaround uses this option.
Go to C:\Program Files\Google\Chrome\Application
Open command prompt
Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"

@junaidulqayyumqureshi
Copy link
Author

junaidulqayyumqureshi commented Aug 15, 2021

Transfer data from one server to another

Copy files from one SSH to another SSH server

scp /path/to/file username@a:/path/to/destination

Step 1:
Zip the product

zip -r product.zip /var/www/product

Step 2:
Take db dump on host server

mysqldump -u root -p spencer > /var/www/exported.sql

Step 3:
Transfer it to new server

scp /var/www/spencer.zip root@{ipaddresss}:/var/www/product-destination-on-remote-server

@junaidulqayyumqureshi
Copy link
Author

junaidulqayyumqureshi commented Aug 17, 2021

Import Export MySQL DB Command Line

Export Dump.sql WITH/WITHOUT SCHEMA
mysqldump -u root -p DB_NAME > /var/www/exported.sql

mysqldump -u root -p --no-data DB_NAME > /var/www/exported.sql

Import Dump.sql
mysql -u root -p database_name < file.sql

@junaidulqayyumqureshi
Copy link
Author

Find string/substring linux

grep -rnw '/var/www/project' -e 'stringtosearch'

@junaidulqayyumqureshi
Copy link
Author

junaidulqayyumqureshi commented Mar 13, 2023

NodeJS Worker Threads

main.js

const { Worker } = require('worker_threads');
const worker = new Worker('./wthread.js');
worker.on('message', (msg) => {
    console.log(`Msg: ${JSON.stringify(msg)}`);
});
// worker.on('error', reject);
worker.on('exit', (code) => {
    if (code !== 0)
        throw new Error(`stopped with  ${code} exit code`)
})

wthread.js

const { workerData, parentPort } = require('worker_threads')

parentPort.postMessage({ "StartedAt": workerData })
------ Code Logic ------
parentPort.postMessage({ result: result })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment