Wednesday, 12 February 2025

Laravel find string in table and columns

 This code will iterate to all tables and columns


$excludedColumns = array("created_at", "updated_at", "deleted_at","order","key");
$tables = DB::select('SHOW TABLES');
foreach ($tables as $table) {

$tableName = data_get($table,'Tables_in_XXXX','');
$columns = Schema::getColumnListing($tableName);
foreach ($columns as $column) {
if (!in_array($column, $excludedColumns)) {
$sqlString = "select count(*) as total from $tableName where `$column` like '%$searchString%'";

$all = DB::select(($sqlString));
$x = json_decode(json_encode($all), true);

$cnt = $x[0]['total'];
if ($cnt > 0) {
Log::info("select * from $tableName where `$column` like '%$searchString%'");
}
}
}
}
Share:

Tuesday, 11 February 2025

Laravel Cache on Redis

Deleting laravel cache when redis is applied



Assuming the Laravel cache used redis
$roles = Cache::store('redis')->rememberForever(
"roles-123456",
function () {
return Role::where('team_id', 12345)
->
get();
}
);


Cache can only be cleared by


Cache::store('redis')->forget("roles-123456");




Share:

Wednesday, 20 September 2023

Laravel Rule Validations

Laravel validations

$errorMessage = "NFL Competition already exist for year $this->year and with the selected competition type.";

return [

    'name' => 'string',
    'abbreviation' => 'required|max:10',
    'year' => 'required|digits:4|integer|min:1900|max:' . (date('Y') + 1),
    'competition_type_id' => ['required', 'string', new IsCompositeUnique('basketball_competitions', ['year' => $this->year, 'competition_type_id' => $this->competition_type_id], $this->competition_id, $errorMessage)],

];





<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class IsCompositeUnique implements Rule
{
/**
* @var string
*/
private $tableName;
/**
* @var array
*/
private $compositeColsKeyValue = [];
/**
* @var mixed|null
*/
private $rowId;

private $errorMessage;

/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(string $tableName, array $compositeColsKeyValue, $rowId = null, $errorMessage = null)
{
$this->tableName = $tableName;
$this->compositeColsKeyValue = $compositeColsKeyValue;
$this->rowId = $rowId;
$this->errorMessage = $errorMessage;
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value): bool
{
if ($this->rowId) {
$record = DB::table($this->tableName)->where($this->compositeColsKeyValue)->first();
$passess = !$record || ($record && $record->id == $this->rowId);
} else {
$passess = !DB::table($this->tableName)->where($this->compositeColsKeyValue)->exists();
}

return $passess;
}

/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
if ($this->errorMessage) {
return $this->errorMessage;
}
$colNames = '';
foreach ($this->compositeColsKeyValue as $col => $value) {
$colNames .= $col . ', ';
}
$colNames = rtrim($colNames, ', ');

return "The combination of $colNames must be unique.";
}
}
Share:

Monday, 26 June 2023

Laravel Nova ReadOnly Problems

 On Laravel Nova,   when creating record field with readonly and default values are not submitted.  This is the correct way to work around it.


Text::make("Field Name", 'field_name')
->withMeta(
[
'extraAttributes' => ['readonly' => true],
'value' => $this->field_name ?? 'Default Value'
]), 
Share:

Thursday, 19 May 2022

PHP Regex Sample Code


A regular expression (shortened as regex or regexp or rational expression) is a sequence of characters that specifies a search pattern in the text.

A good testing site is 

https://infoheap.com/php-preg_match-online/ 

Examples of regex for password

PHP Version

/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z])(?=\S*[\W]).{8,}$/


Must have special characters

(?=\S*[\W])


Must have a number

(?=.*\\d)


Must have uppercase and lowercase

(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z])


Some reference

https://stackoverflow.com/questions/8141125/regex-for-password-php

https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a

Share:

Friday, 22 April 2022

Tuesday, 8 March 2022

Wednesday, 9 February 2022

Changing .env Programatically

With great powers comes great responsibility, changing .env values in the server were great but if you don't have access to it this code might come in handy.

In your route, where key is the key, and value will be the new env value


Route::get('changeenv/{key?}/{value?}',"controller@methodname"); 

In your controller


  public function changeEnv($key, $value)
    {
        $path = app()->environmentFilePath();

        $escaped = preg_quote('=' . env($key), '/');

        file_put_contents($path, preg_replace(
            "/^{$key}{$escaped}/m",
            "{$key}={$value}",
            file_get_contents($path)
        ));

        return "env change successfully " .  env($key);
    }

In your browser, you could type this to change the .env's CAPTCHA value

https://mysite.com/changeenv/CAPTCHA/new_value
Share:

Tuesday, 8 February 2022

Laravel SMTP Settings for Different Mail Service Provider

Laravel SMTP Settings for Different Mail Service Provider MAILHOG

brew update && brew install mailhog
For Laravel .env

MAIL_DRIVER=smtp
MAIL_HOST=0.0.0.0
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
Run in Terminal

mailhog
Testing Email Open this link Mailhog UI

Just continue sending email
Share:

Monday, 7 February 2022

Makefile miscellaneous commands

Some miscellaneous commands for makefile This command will cd to a page and run command inside the page, if successful succeeding commands will be called.


build:adminx	font	js

js:
	npm run build

font:
	npm run gulp iconfont

adminx:
	cd admin; npm run build
    
    
Share:

Monday, 31 January 2022

Thursday, 27 January 2022

PHP Google GeoCoding Getting Latitude & Longitude

  
private function getGeoLocation($address)  
   {  
     try {  
       $url = 'https://maps.google.com/maps/api/geocode/json';  
       $address = str_replace(["'", '"'], " ", $address);  
       $address = str_replace([" ", " "], "+", $address);  
       $query_array = array(  
         'address' => $address,  
         'key' => env('GOOGLE_MAP_API_KEY')  
       );  
       $query = http_build_query($query_array);  
       $content = file_get_contents($url . '?' . $query);  
       $output = json_decode($content);  
       $result = [];  
       if ($output->status == "OK") {  
         $result['latitude'] = $output->results[0]->geometry->location->lat;  
         $result['longitude'] = $output->results[0]->geometry->location->lng;  
       }  
       return $result;  
     } catch (\Exception $ex) {  
       return [];  
     }  
   }  
Share:

Saturday, 13 March 2021

Creating 2 folder location on Vagrant homestead.yaml



---

ip: "192.168.10.10"

memory: 2048

cpus: 2

provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:

    - ~/.ssh/id_rsa

folders:

    - map: /Users/junedc/Desktop/AMyProject/
      to: /home/vagrant/code1/


    - map: /Users/junedc/Desktop/AMyProject2/
      to: /home/vagrant/code2/

sites:

    - map: laracartvue.test
      to: /home/vagrant/code1/laracart-vue/public

    - map: backend.test
      to: /home/vagrant/code2/backend_template/public

    - map: laravel8.test
      to: /home/vagrant/code2/laravel8/public

ssl:

    - true

databases:
    - homestead

features:
    - mariadb: false
    - ohmyzsh: false
    - webdriver: false


Share:

Monday, 19 October 2020

Creating a Secured Laravel Homestead SSH

Open Homestead.yaml file and add SSL = true it will create crt file in /etc/nginx/ssl


Sample Homestead.yaml file
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:

    - map: /Users/junedc/Desktop/AMyProject/

      to: /home/vagrant/code1/


    - map: /Users/junedc/Desktop/AMyProject2/

      to: /home/vagrant/code2/


sites:

    - map: backend.test

      to: /home/vagrant/code1/backend_template/public


    - map: laravel8.test

      to: /home/vagrant/code2/laravel8/public


ssl:
     - true

Some commands to generate ssh key,  create a certificate, reload the new settings

xxxx
 ssh-keygen -t rsa
 vagrant up 
 vagrant ssh 
 cp cafefrends.test.crt /home/vagrant/code/cafefrends 
 
 vagrant halt
 vagrant reload --provision


In your mac KeyChain Access Add the crt file that was created in the previous step and set the SSL to 'Always Trust'
Share:

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:

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.