Howtos

Framework HOWTOs

Debug Eloquent with bindings

<?php
public static function getEloquentSqlWithBindings($query)
    {
        return str_replace_array('?', $query->getBindings(), $query->toSql());
    }

Time tracking for PhpStorm

1) Darkyen

https://github.com/Darkyenus/DarkyenusTimeTracker

2) Wakatime

https://wakatime.com/

Post subscription creation, queue event to commission server

How to include Javascript and CSS on every page in a Laravel app

On page:

@stack('per_page_css')

and then at the bottom of a page (even if you’re injecting at the top)

@endsection

@push('per_page_css')
    <link rel="stylesheet" type="text/css" href="css/compare.css">
@endpush

Artisan Parameters

Complex interaction between posting JSON and retrieving it

  1. Post JSON
  2. Request Object retrieves
  3. request()->all() make an array
  4. $params = json_decode(json_encode($params)); turns it back into object
  5. data->value

How to add default / current timestamp to newly created data fields in migrations

$table->timestamp('created_at')->useCurrent();

Laravel Event Listeners

art make:listener -e=UploadCreated --queued NewUpload

MySQL HowTOs

Raw Queries in Laravel:

<?php
 private function transformDates() {
        DB::statement(
            "update standard_bank_schemas set date = concat(substr(date, 1, 4), '-', substr(date,5 ,2), '-', substr(date, 7,2))"
        );
    }

PHP - General

How to do word wrap in PHP

<?php
Text::make('Name')->displayUsing(function ($string) {
                if (strlen($string) > 40) {
                    $string = wordwrap($string, 40);
                    $string = substr($string, 0, strpos($string, "\n"));
                    $string .= "...";
                }
                return $string;
            }),

Laravel

Permissions

Nova

How to remove permission to edit files.

TBA

BAS Cron

  • Retrieve root transactions
  • Check ticket emails

cd /home/fintechs/domains/bas.fintechsystems.net/bas && php artisan schedule:run >> /dev/null 2>&1

Terminology

Difference between a client and a customer

The nouns client and customer are sometimes used interchangeably—especially by businesses seeking to show customers extra respect by referring to them as “clients”—but the words differ in their conventional definitions.

A client is someone who engages the services of a professional. For example, lawyers, plumbers, freelance writers, accountants, and web designers often work for clients.

A customer buys goods or services from a business (rather than an individual or group of professionals).

Localization

Currency

How to display currency properly in Nova:

Install Money component then:

<?php
Money::make('Total', 'ZAR')->locale('en-ZA')->storedInMinorUnits();

How to display currency properly in PHP:

<td align="right">{{  money_format('%n', $invoice->total ) }}</td>

Queues not working

Queues not working but everything seems correct?

php artisan config:cache

Default Seeder

<?php
    DB::table('users')->insert([
        'name' => 'Eugene van der Merwe',
        'email' => 'eugenevdm@gmail.com',
        'password' => bcrypt('password'),
    ]);

Challenging topics in Laravel

Alexa

DOTNET

Async Web Request callbacks

Mysql find_in_set

$task_list = TaskList::where('name', $id)->orWhereRaw("FIND_IN_SET( '$id',alias) > 0")->first();

JSON Standard formats:

https://stackoverflow.com/questions/12806386/standard-json-api-response-format

https://github.com/omniti-labs/jsend

Type Description Required Keys Optional Keys
success All went well, and (usually) some data was returned. status, data
fail There was a problem with the data submitted, or some pre-condition of the API call wasn’t satisfied status, data
error An error occurred in processing the request, i.e. an exception was thrown status, message code, data

Examples

 * @response {
 *  "status": "success",
 *  data: [
 *  "name": "Jessica Jones",
 *  "roles": ["admin"]
 *  }
 * @response 404 {
 *  "status: : "error",
 *  "message": "Sorry $name, I cannot find a list called $id.",
 * }

Laravel get IPs

How to get the current client IP (local versus remote):

request()->ip() versus $_SERVER['SERVER_ADDR']

Laravel - receive JSON direct from Alexa

If you don’t use json() you end up with a Symfony object that’s impossible to decode

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(Request $request, $id)
    {
        $data = $request->json()->all();
    }
}

Nova General

How to reference a model in a resource

<php
Text::make('Created', function () {
    return $this->created_at->diffForHumans();
})

Nova Packages

These are packages we currently use in projects:

Tabs

BO

Multiple custom dashboards

BO

Belongs To Depend

No project as of yet

CVsmart - https://novapackages.com/packages/wehaa/custom-links

VueJS

Include two rows in a v-for

<table>
   <tbody>
     <template v-for="item in items">
         <tr><td>1</td><td>2</td></tr>
         <tr><td colspan="2"></tr>
     </template>
   </tbody>
</table>

Reference - https://stackoverflow.com/questions/49012851/vue-js-v-for-on-two-table-rows

Git

Store credentials insecurely

git config credential.helper store

First create user then grant

create user 'user1' identified by 'ChangeMe' password expire;

grant all privileges on *.* to 'user1'@'%' with grant option;

Conditionally redirect on login

Override authentication in LoginConroller.php

<?php
protected function authenticated(Request $request, $user)
    {
        if ( $user->hasRole('Admin') ) {
            return redirect('/admin');
        }
        return redirect('/home');
    }

jquery

How to go a get and a post at the same time

Given URL

http://cvsmart.test/post?affiliate=mycode

HTML

<form id="form" method="POST" action="/post">
    @csrf
    <input name="name">
</form>

jQuery

    $("#form").submit(function () {
        let searchParams = new URLSearchParams(window.location.search);
        let param = searchParams.get('affiliate');
        $("<input />").attr("type", "hidden")
            .attr("name", "affiliate")
            .attr("value", param)
            .appendTo(this);
        return true;
    });

Reference: - https://stackoverflow.com/questions/19491336/get-url-parameter-jquery-or-how-to-get-query-string-values-in-js

How to include jQuery in a Laravel page

In your master layouts file, at the bottom, before body close tag:

In app.blade.php

@stack('scripts')

On every page:

@push('scripts')
<script>
    // Your script
</script>

How to enable multiple RDP connections

Run gpedit.msc

Local Computer Policy - Administrative Templates - Windows Components - Remote Desktop Services - Remote Desktop Session Host - Connections

Number of Connections: Enabled: 2 to 999999

Restrict: Disabled

Run gpupdate

Guzzle HTTP

Why not just use file_get_contents?

Guzzlehttp provides a host of additional functionality like abstraction which is useful when you’re working with APIs.

To install:

composer require guzzlehttp/guzzle

Two things to watch out if you’re using Guzzle:

  1. Old versions. Try to stick with version 6 because things change all the time. The way things were done in prior versions differs a lot. https://stackoverflow.com/questions/17658283/catching-exceptions-from-guzzle

  2. Watch out for Exception handling built into Guzzle. You might want to turn it off to get better output.

The easiest is just to disable it when you instantiate the client:

$client = new \GuzzleHttp\Client(['http_errors' => false]);

But be aware! Your exceptions must be precise:

In the block below \GuzzleHttp\Exception\ClientException $e took me hours to figure out! Additionally the actual error was no API key, and only config:clear sorted this out!

<?php
$client = new \GuzzleHttp\Client(['http_errors' => 'false']);
        try {
            $request = $client->get(self::api_url . '/transactions', [
                'auth'        => [env('ROOT_API_KEY'), null]
            ]);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            Log::error($e->getResponse()->getBody()->getContents());
            return false;
        }
  1. How to post JSON:
<?php

$client = new \GuzzleHttp\Client(['http_errors' => false]);

$response = $client->post(config('api.pickup_url') . "command/receive",
    [
        'json' => [
            'model'          => $m,
            'Id'             => $data->Id,
            'XMLData'        => $data->XMLData,
            'ChangeDateTime' => $data->ChangeDateTime,
        ]
    ]);
    $response = $response->getBody()->getContents();
  1. As you can see in the above, also use ->getContents()

  2. To post XML: ```php <?php $options = [ ‘headers’ => [ ‘Content-Type’ => ‘text/xml; charset=UTF8’, ], ‘body’ => $xml, ];

$response = $client->request(‘POST’, $url, $options);


```php
<?php
    $request = new Request(
        'POST', 
        $uri,
        ['Content-Type' => 'text/xml; charset=UTF8'],
        $xml
);
  1. To Get JSON

Here is a simple API example to do a GET:

<?php

require_once "vendor/autoload.php";

use GuzzleHttp\Client;

class Bo
{

    public static function getTask($task)
    {
        $response = self::api("http://bo.test/api/v1/tasks/$task");
        return $response;
    }

    private static function api($url)
    {
        $client = new Client();
        $res    = $client->request('GET', $url);
        return json_decode($res->getBody());
    }

}

References: - Back Office APIs - http://docs.guzzlephp.org/en/stable/ - https://stackoverflow.com/questions/34726530/proper-way-to-send-post-xml-with-guzzle-6

Work with large XML

SQL in Linux / PHP

Install ODBC Drivers and Tools

https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017#microsoft-odbc-driver-17-for-sql-server

Test

sqlcmd -S host_name -U username -P password

use db_name
go
select * from orders
go

sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv

On PHP 7.6, copy to ‘/usr/lib/php/20170718/pdo_sqlsrv.so’

/pdo_sqlsrv.so: undefined symbol: php_pdo_register_driver

https://github.com/Microsoft/msphpsql/releases

php_pdo_sqlsrv_72_nts.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

Notice the repeat upstairs???

The breakthrough:

sudo echo "extension= pdo_sqlsrv.so"  > $(php --ini | grep "additional .ini" | sed -e "s|.*:\s*||")/99-sqlsrv.ini
sudo echo "extension= sqlsrv.so"     >> $(php --ini | grep "additional .ini" | sed -e "s|.*:\s*||")/99-sqlsrv.ini

Resize PNG Online

Chrome ERR_UNSAFE_PORT

http://webserver:139 give ERR_UNSAFE_PORT

$ google-chrome --explicitly-allowed-ports=139

How to use Composer Offline

Create repositories section and then artifacts directory and put files in there. See this post:

Check Laravel version

Do this:

$ art --version
Laravel Framework 5.7.26

or this:

$ art -V
Laravel Framework 5.7.26

Eloquent

firstOrCreate/ firstOrNew

<?php
// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
$flight = App\Flight::firstOrCreate(
    ['name' => 'Flight 10'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

firstOrNew is similar to firstOrCreate, but the record is not persisted and needs to be saved.

updateOrCreate

<?php

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

Microsoft SQL

On Windows

extension=php_sqlsrv_73_ts_x64
extension=php_pdo_sqlsrv_73_ts_x64

Download version 4 http://www.microsoft.com/en-us/download/details.aspx?id=20098 Download 5.6 for PHP 7.3 and use x64 https://docs.microsoft.com/en-gb/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017

Reference: https://stackoverflow.com/questions/30736601/fatal-error-call-to-undefined-function-sqlsrv-connect-in-c-xampp-htdocs

On Linux

How to get Microsoft SQL working on a Laravel Linux installation

If you get this error ...could not find driver (SQL: select * from...

OS Prep 1

Instructions for Ubuntu 18.04

apt install pear
apt-get install g++
sudo apt install unixodbc-dev
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv

Laravel Valet for Linux:

vi /etc/php/7.2/fpm/php.ini

add extension=sqlsrv.so and extension=pdo_sqlsrv.so

The files are in /usr/lib/php/20170718/pdo_sqlsrv.so but they will be picked up.

References:

OS Prep 2

Do this:

sudo apt-get install freetds-common freetds-bin unixodbc php7.2-sybase

Add a new section in your .env

MSSQL_DB_CONNECTION=sqlsrv
MSSQL_DB_HOST=
MSSQL_DB_PORT=1433
MSSQL_DB_DATABASE=
MSSQL_DB_USERNAME=
MSSQL_DB_PASSWORD=

Amend your database configuration /config/database.php

'sqlsrv' => [
            'driver'         => 'sqlsrv',
            'url'            => env('DATABASE_URL'),
            'host'           => env('MSSQL_DB_HOST', 'localhost'),
            'port'           => env('MSSQL_DB_PORT', '1433'),
            'database'       => env('MSSQL_DB_DATABASE', 'forge'),
            'username'       => env('MSSQL_DB_USERNAME', 'forge'),
            'password'       => env('MSSQL_DB_PASSWORD', ''),
            'charset'        => 'utf8',
            'prefix'         => '',
            'prefix_indexes' => true,
        ],

    ],

Sample code

<?php 
$data = DB::connection('sqlsrv')->select("SELECT * FROM Customer"); // 52 records 1 minute 30 seconds