Showing posts with label Laravel-Lumen. Show all posts
Showing posts with label Laravel-Lumen. Show all posts

Tuesday, 26 March 2019

Resolve an issue to insert explicit value for identity column in SQL table asking for IDENTITY_INSERT to set ON/OFF in PHP (Laravel)

The following methods to control the `IDENTITY_INSERT` to ON/OFF for SQL table seeding process in PHP (Laravel) :
    
    function setIdentityInsert($table, $onStatus = true)
    {
        $status = $onStatus ? 'ON' : 'OFF';

        $this->sqlConnection->unprepared("SET IDENTITY_INSERT $table $status");
    }

    function insertTableData($table, $data)
    {
        return $this->sqlConnection->table($table)->insert($data);
    }

    function seedTable($table, $hasAutoIncrementPrimaryKey = false, $data = [])
    {
        if ($hasAutoIncrementPrimaryKey) {
            $this->setIdentityInsert($table);
            $response = $this->insertTableData($table, $data);
            $this->setIdentityInsert($table, false);

            return $response;
        }
        else {
            return $this->insertTableData($table, $data);
        }
    }

Note: Generally, the table requires to have an auto-increment primary key to set Identity Insert to `ON`, that's why I have the `$hasAutoIncrementPrimaryKey` flag. Otherwise, seeding may throw an error as:
    
    SQLSTATE[HY000]: General error: 544 Cannot insert explicit value for
    identity column in table 'test_table_name' when IDENTITY_INSERT is set to
    OFF. [544] (severity 16) [(null)]
Hope this helps!

Thursday, 21 February 2019

Laravel - PHPUnit - run single test class or method

The following command runs the test on a single method: (e.g. we are testing the `testCreateUser()` method here)
vendor/bin/phpunit --filter testCreateUser UserControllerTest tests/feature/UserControllerTest.php
vendor/bin/phpunit --filter methodName ClassName path/to/file.php
Further, lets say you want to test a ClassName which exists into two location:
tests/unit/UserControllerTest.php // contains 3 tests
tests/feature/UserControllerTest.php // contains 2 tests
In this case, you simply run below command which will check for all the test on both location.
vendor/bin/phpunit --filter UserControllerTest

-----Output---------
Time: 2.56 seconds, Memory: 30.00MB

OK (5 tests, 22 assertions)
Please note, if you have phpunit available globally on your machine, you can simply run
phpunit --filter 

# instead of 
vendor/bin/phpunit --filter
Stackflow resource.

Thursday, 31 January 2019

Rename all existing files on AWS S3 Bucket using Laravel Storage library

Follow below steps to rename existing files on a selected directory on S3 Bucket.

1. Lets say your config/filesystems.php looks like this:
'disks' => [
  's3_test_bucket' => [
        'driver' => 's3',
        'key'    => env('AWS_KEY', 'your_aws_key_here'),
        'secret' => env('AWS_SECRET','your_aws_secret_here'),
        'region' =>  env('AWS_REGION', 'your_aws_region_here'),
        'version' => 'latest',
        'bucket'  => 'my-test-bucket',
  ],
];

2. Let's say, you have my-test-bucket on your AWS S3.

3. Lets say you have following files inside the my-test-bucket/test-directory directory.
i.e.
- test-files-1.csv
- test-files-2.csv
- test-files-3.csv

3. Call below function to rename existing files on a selected directory on S3 Bucket.
$directoryPath = 'test-directory';
$storage = new MyStorageRepository();
$storage->renameAnyExistingFilesOnImportDirectory('my-test-bucket', 'test-directory');

4. Output: files should be rename as below on my-test-bucket/test-directory directory:
- test-files-1--1548870936.csv
- test-files-2--1548870936.csv
- test-files-3--1548870936.csv

5. Include the below library class or methods on your class and you should be good.

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;

class MyStorageRepository
{
    public function renameAnyExistingFilesOnImportDirectory($bucket, $directoryPath)
    {
        $directoryPath = App::environment() . '/' . $directoryPath;
        $storage = Storage::disk('s3_test_bucket');

        $suffix = '--' . time(); // File suffix to rename.

        if ($storage->exists($directoryPath)) {
            $this->renameStorageDirectoryFiles($directoryPath, $storage, $suffix);
        }
    }

    private function getNewFilename($filename, $suffix = null)
    {
        $file = (object) pathinfo($filename);

        if (!$suffix) {
            $suffix = '--' . time();
        }

        return $file->dirname . '/' . $file->filename . $suffix . '.' . $file->extension;
    }

    private function renameStorageDirectoryFiles($directoryPath, $storage = null, $suffix = null, $filesystemDriver = null)
    {
        if (!$storage) {
            $storage = Storage::disk($filesystemDriver);
        }

        // List all the existing files from the directory
        $files = $storage->files($directoryPath);

        if (count($files) < 1 ) return false;

        foreach($files as $file) {
            // Get new filename
            $newFilename = Helpers::getNewFilename($file, $suffix);

            // Renamed the files
            $storage->move($file, $newFilename);
        }
    }
}
  
Also, copy of ref here

Thursday, 24 January 2019

Laravel Method to check if the given record id exists on DB table or not.

public function isModelRecordExist($model, $recordId)
{
    if (!$recordId) return false;

    $count = $model->where(['id' => $recordId])->count();

    return $count ? true : false;
}

// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);

// Outcome: true | false

Hope it helps!

Tuesday, 13 November 2018

SAML Auth login issue on local - undefined logger()

(1/1) FatalThrowableError
Call to undefined function App\Http\Controllers\logger()

in SamlController.php line 85
at SamlController->acs()
at call_user_func_array(array(object(SamlController), 'acs'), array())
in BoundMethod.php line 29


Enable the Saml debugger by adding the `SAML2_DEBUG=true` on .env.

Then, found the following error:
openssl_x509_read(): supplied parameter cannot be coerced into an X509 certificate!
Whoops, looks like something went wrong.
(1/1) FatalThrowableError
Call to undefined function App\Http\Controllers\logger()

in SamlController.php line 87
at SamlController->acs()
at call_user_func_array(array(object(SamlController), 'acs'), array())
in BoundMethod.php line 29
at BoundMethod::Illuminate\Container\{closure}()
in BoundMethod.php line 87


Resolved the issue after updating with the correct `SAML2_IDP_X509CERT` value.

Thursday, 19 October 2017

To create a custom token password reset in Laravel 5.5 (Or Lumen)

Please use the below passwordResetToken() function to get the token for password reset for custom use.

namespace App\Traits;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Password;

trait ResetPasswordTrait 
{
    ...
    ...
    ...
    ...

    /**
     * Get the token for password reset and update the token in the database table.
     *
     * @return string|null
     */
    public function passwordResetToken($user)
    {
        $this->broker = 'users';

        $broker = $this->getBroker();

        return Password::broker($broker)->createToken($user);
    }

    /**
     * Get the broker to be used during password reset.
     *
     * @return string|null
     */
    public function getBroker()
    {
        return property_exists($this, 'broker') ? $this->broker : null;
    }

}


// Reuse in the class
use App\Traits\ResetPasswordTrait;

class NewUserAccount 
{

    use ResetPasswordTrait;

    // Sample function to print the password reset token
    public function printPasswordResetToken(Request $request)
    {
        $user = User::find( $request->input('id') );
        $passwordResetToken = $this->passwordResetToken($user);
        print_r($passwordResetToken);
    }

}

Wednesday, 5 April 2017

Generating the Laravel/Lumen Migrations from ER Diagram Model using MySQLWorkbench

To install the Migration Exporter from MySQL Workbench

Install thehttps://github.com/beckenrode/mysql-workbench-export-laravel-5-migrations/blob/master/export-laravel-5-migrations.py from Workbench > Scripting > Install Plugin/Module and browse the `export-laravel-5-migrations.py` file.

Then, go to Workbench > Tools > Catalog > Export Laravel 5 Migration and click on "Save the Migrations to the Folder..."

However got the following error: (Workbench > Help > Show Log File)
Error during "Export Laravel 5 Migration" 
Then, review the relationship index and foreign keys relations and amended few foreign keys which are not properly selected the reference columns.

Afterwards, tried generating the migration using above method, ultimately able to generate the migration.
However, found missing foreign keys relationship generated migration files.

To generate Laravel Migrations from MySQL Workbench:

To build the migrations with foreign constrains using following steps:
  1. Export the model using MySQL Workbench > File > Export > Forward Engineer approach as sample_database.sql file
  2. Create the database called 'sample_database'.
  3. Next, Import the sample_database.sql file into the above created database to build tables, which will populate all tables from the script. (you can also directly execute all the scripts from that .sql file instead, from the Query Builder)
    Note: Please make sure all the foreign keys relationships are created along with tables, once you find all the relationship are in place.
  4. Then, go to the MySQL Workbench > Database > Reverse Engineer, and establish the connection and select the database to regenerate the Model (ERD).
    This allows the MySQL Workbench to propagate the Tables' objects correctly which supports to generate the migrations.
  5. Lastly, go to Workbench > Tools > Catalog > Export Laravel 5 Migration and click on "Save the Migrations to the Folder..."
    If you already haven't install the Laravel 5 Migration plugin, refer above.

Tuesday, 4 April 2017

Configure Entrust on Laravel-lumen

## Configure Entrust on Laravel-lumen * In order to install Laravel 5 Entrust, just add the following to your composer.json. Then run composer update:
    "zizaco/entrust": "5.2.x-dev"
    
* Open your `bootstrap/app.php` and add the following to the providers array:
    $app->register(Zizaco\Entrust\EntrustServiceProvider::class);
    
* Create new `config/` directory on the project root folder. * Then, add the following package on `composer.json`:
    "laravelista/lumen-vendor-publish": "^2.0"
    
then, run
    composer update
    
* Create the `app/helpers.php` file and add the below function inside it.
    if (! function_exists('config_path')) {
        /**
         * Get the configuration path.
         *
         * @param  string  $patha
         * @return string
         */
        function config_path($path = '')
        {
            return app()->basePath() . DIRECTORY_SEPARATOR . 'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
        }
    }
    
* Add the following code into the `composer.json` inside the `autoload` after the `psr-4`
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
    
* Comment out the following line on `vendor/zizaco/entrust/src/Entrust/EntrustServiceProvider.php`
    //$this->bladeDirectives();
    
And, run the dump autolaod command:
    composer dump-autoload -o
    
* Then run the vendor publish command:
    php artisan vendor:publish