Thursday 31 October 2019

Laravel creating an interface and implementation dynamically

Somehow you need to run a different implementation depending on system environment This is what i have done for one of my case
In your .env file

DOCUMENT_INTERFACE=GoogleCloud
#DOCUMENT_INTERFACE=LocalStorage
In my AppServiceProvider.php


   use Illuminate\Support\Facades\App;
   public function register()
    {
        $this->app->bind(DocumentInterface::class, function () {
            $className = 'Path\To\Interfaces' . '\\' . env('DOCUMENT_INTERFACE') . 'Implementation';
            $class = App::make($className);
            return new $class();
        });
    }
       
DocumentInterface.php

interface DocumentInterface
{
    public function create(DocumentUpload $documentUpload);
}

GoogleCloudImplementation.php


class GoogleCloudImplementation implements DocumentInterface
{
    public function create(DocumentUpload $documentUpload)
    {
       
    }
}

LocalStorageImplementation.php


class LocalStorageImplementation implements DocumentInterface
{
    public function create(DocumentUpload $documentUpload)
    {
       
    }
}

Share:

Thursday 17 October 2019

Command needed when installing MySQL

MySQL command not found? Looking tru this forum https://stackoverflow.com/questions/10577374/mysql-command-not-found-in-os-x-10-7

    echo 'export PATH="/usr/local/mysql/bin:$PATH"' >> ~/.bash_profile


To connect to MySQL prompt


    mysql -u root -p

Change the MySQL password permanently


    mysql -u root -p
    ALTER USER `root`@`localhost` IDENTIFIED BY 'password', `root`@`localhost` PASSWORD EXPIRE NEVER;

Share:

Wednesday 24 July 2019

The Date Problem for Laravel and Regional Settings

For every Laravel application birthday should be displayed as it was saved. It should have a type 'date' and those 'created_at' should be 'datetime'
From New Zealand the record could be created Friday but for Cooks Island the record can be Thursday entry.
This is where PHP Carbon date comes to uses and Javascript Moments.

Install Moment and format as required. In VueJS create a filter


import moment from 'moment';

import moment from 'moment';
import {VueConstructor} from 'vue';

export const filters = {
  period: (value: string): string => {
    if (!value) return '-';
    return moment(value).format('MMM YYYY');
  },
  periodFullMonth: (value: string): string => {
    if (!value) return '-';
    return moment(value).format('MMMM YYYY');
  },
  date: (value: string): string => {
    if (!value) return '-';
    return moment.utc(value).local().format('DD-MM-YYYY');
  },
  absoluteDate: (value: string): string => {
    if (!value) return null;
    return moment(value).format('DD-MM-YYYY');
  },
};

export const createFilters = (vue: VueConstructor) => {
  vue.filter('period', filters.period);
  vue.filter('date', filters.date);
  vue.filter('absoluteDate', filters.absoluteDate);
  vue.filter('periodFullMonth', filters.periodFullMonth);
};

export default filters;

You might need to format the fields requests when saving


        Model::create([
            'began_at' => Carbon::createFromFormat('d-m-Y', $request->get('began_at')),
            'terminated_at' => $request->get('terminated_at'),
        ]);
Database Migration Scripts


         $table->dateTime('created_at');  
         $table->date('birthdate');  
Share:

Monday 8 July 2019

Laravel Eloquent Relationship 101

Laravel uses the default 'id' as the primary key when defining table.
With this in mind we will be having difficulty especially if we are using Laravel eager loading style as stated in stackoverflow.
In order to have that peace of mind when loading fields it is safer to create a different id key for different table. This is how to go with that approach.
For our parent migration script we have
 
<?php  
 use Illuminate\Support\Facades\Schema;  
 use Illuminate\Database\Schema\Blueprint;  
 use Illuminate\Database\Migrations\Migration;  
 class CreateAuthorsTable extends Migration  
 {  
   public function up()  
   {  
     Schema::create('authors', function (Blueprint $table) {  
       $table->bigIncrements('au_id');  
       $table->string('name');  
       $table->timestamp('birth_date');  
       $table->unsignedBigInteger('au_st_id');  
       $table->timestamps();  
     });  
   }  
   public function down()  
   {  
     Schema::dropIfExists('authors');  
   }  
 }  
For our child table, we will have
 
<?php  

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->bigIncrements('bk_id');
            $table->unsignedBigInteger('bk_au_id');
            $table->string('title');
            $table->timestamp('published_date')->nullable();
            $table->timestamps();

            $table->foreign('bk_au_id')->references('au_id')->on('authors')->onDelete('cascade');
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('books');
    }
}


To complete the migration script for address
 
<?php  

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAuthorAddressesTable extends Migration
{
    public function up()
    {
        Schema::create('author_addresses', function (Blueprint $table) {
            $table->bigIncrements('aud_id');
            $table->unsignedBigInteger('aud_au_id');
            $table->string('city')->nullable();
            $table->string('address')->nullable();
            $table->timestamps();

            $table->foreign('aud_au_id')->references('au_id')->on('authors')->onDelete('cascade');
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('author_addresses');
    }
}


This is how to define the relationship that an Author can write 1 or more books. The relationship also shows that he lives in just one (1)address at a time
 

<?php  

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Author extends Model
{
    protected $primaryKey = 'au_id';

    public function books(): HasMany
    {
        return $this->hasMany('App\Book', 'bk_au_id', 'au_id');
    }

    public function address(): HasOne
    {
        return $this->hasOne('App\AuthorAddress','aud_au_id','au_id');
    }
}

This is to define that a book belongs to an author
 

<?php  

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Book extends Model
{
    protected $primaryKey = 'bk_id';

    public function author(): BelongsTo
    {
        return $this->belongsTo('App\Author', 'bk_au_id', 'au_id');
    }
}

Share:

Thursday 13 June 2019

Useful terminal commands for MAC, Ubuntu or Windows

Search specific type of file in all folder

  • find ~ -type f -name '*pdf'
  • find ~ -iname '*pdf'

Search specific type of file in current folder
  • find . -iname '*pdf'
Make file executable
  • chmod +x file.xx'
Run PHPFixer on current folder
  • php-cs-fixer fix --diff --dry-run --stop-on-violation -v --using-cache=no
  • php-cs-fixer fix --stop-on-violation -v --using-cache=no
Make your git branch prefix
  • curl https://gist.githubusercontent.com/bartoszmajsak/1396344/raw/bff6973325b159254a3ba13c5cb9ac8fda8e382b/prepare-commit-msg.sh > .git/hooks/prepare-commit-msg && chmod u+x .git/hooks/prepare-commit-msg
Delete node_modules from a certain folder
  • copied from https://stackoverflow.com/questions/42950501/delete-node-modules-folder-recursively-from-a-specified-path-using-command-line
  • find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \; 

Open a very large file like log files
  • tail -500 bigfile | less
Show hidden files in mac
  • defaults write com.apple.Finder AppleShowAllFiles true
  • killall Finder

Add entries to a file by using export
  •   echo 'export PATH="/usr/local/opt/php@8.0/bin:$PATH"' >> ~/.zshrc

      echo 'export PATH="/usr/local/opt/php@8.0/sbin:$PATH"' >> ~/.zshrc


Install Python
  • brew install pyenv
  • pyenv install 2.7.18
  • pyenv global 2.7.18

Share:

Monday 27 May 2019

Country Package for Laravel

It is often or not we need a country listing in our package to display in the view or dropdown HTML component. Instead of creating table of coutries we could use a proven PHP package library to do that.

I come across this library league/iso3166 and have use it ever since.

Methods you can use are:


   #to define the library 
   use League\ISO3166\ISO3166;

   #to get all countries
   $countries = (new ISO3166())->all();

   #to get a specific country details and currency for Philippines
   $country => (new ISO3166())->alpha3('PHL');

   #to get a specific country name for Philippines
   $country_name' => ((new ISO3166())->alpha3('PHL'))['name'];


Share:

Wednesday 23 January 2019

PHP Number to Romans Numeral conversion

Just Playing with PHP lately and thought of a Digit to Roman Numerals conversion. This is one of my testing exam before and just recall how I did it.



$romanString = '';
$value = 975;
 do {
   $converted = convertToRoman($value); 
   $value = $converted[0];
   $romanString = $romanString .  $converted[1];
 } while ( $value != 0);

echo $romanString;

 function convertToRoman($number){
    $returnValue = 0;
    $returnString = '';
 $romanArray = [[1000,'M'],[900,'CM'],[100,'C'],[90,'XC'],[50,'L'],[10,'X'],[9,'IX'],[5,'V'],[4,'IV'],[1,'I']];

 foreach ($romanArray as  $value) {
  
       if ($number >= $value[0]) {
            $returnValue = $number - $value[0];
            $returnString = $value[1]; 
            break;
       }        

 }
     
 return array($returnValue,$returnString);
}

Share:

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.