Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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:

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:

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:

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:

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:

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:

Wednesday, 2 May 2018

Complex Laravel Eloquent Example



select   n0y_t_item_description.s_title,
n0y_t_item_description.s_slug as item_slug,
n0y_t_item.d_price         as price,
n0y_t_category_description.s_name,
n0y_t_category_description.s_slug as category_slug,
n0y_t_item_resource.pk_i_id as path_id,
n0y_t_item_resource.s_path as image_path,
n0y_t_item_resource.s_extension as path_ext,
parent_slug from `n0y_t_item` inner join `n0y_t_item_description` on `n0y_t_item_description`.`fk_i_item_id` = `n0y_t_item`.`pk_i_id` inner join `n0y_t_category` on `n0y_t_category`.`pk_i_id` = `n0y_t_item`.`fk_i_category_id` inner join `n0y_t_category_description` on `n0y_t_category`.`pk_i_id` = `n0y_t_category_description`.`fk_i_category_id` inner join `n0y_t_item_resource` on `n0y_t_item_resource`.`fk_i_item_id` = `n0y_t_item`.`pk_i_id` inner join (select pk_i_id, s_slug as parent_slug
from n0y_t_category join n0y_t_category_description on n0y_t_category.pk_i_id = n0y_t_category_description.fk_i_category_id
) as n0y_pCat on `n0y_pCat`.`pk_i_id` = `n0y_t_category`.`fk_i_parent_id` where (`b_active` = '1' and `i_main` = '1') order by RAND() limit 7
         
   
   
   
        $sql = '  xxt_item_description.s_title, 
                  xxt_item_description.s_slug as item_slug, 
                  xxt_item.d_price         as price,
                  xxt_category_description.s_name, 
                  xxt_category_description.s_slug as category_slug,
                  xxt_item_resource.pk_i_id as path_id,
                  xxt_item_resource.s_path as image_path,
                  xxt_item_resource.s_extension as path_ext,
                  parent_slug';

        $sql = str_replace('xx', DB::getTablePrefix(), $sql);


        $joinQry =    "(select pk_i_id, s_slug as parent_slug
                   from xxt_category join xxt_category_description on xxt_category.pk_i_id = xxt_category_description.fk_i_category_id
            ) as xxpCat";

        $joinQry = str_replace('xx', DB::getTablePrefix(), $joinQry);

        $items = DB::table('t_item')
            ->select(DB::raw(
                $sql
            ))
            ->join('t_item_description', 't_item_description.fk_i_item_id', 't_item.pk_i_id')
            ->join('t_category', 't_category.pk_i_id', 't_item.fk_i_category_id')
            ->join('t_category_description', 't_category.pk_i_id', 't_category_description.fk_i_category_id')
            ->join('t_item_resource', 't_item_resource.fk_i_item_id', 't_item.pk_i_id')
            ->where(function ($q) use ($tenDaysAgo, $currentDate) {
                $q->where('b_active', 1)
                   ->where('i_main',1);
//                    ->whereDate('dt_expiration', '>', date($currentDate->toDateTimeString()))
//                    ->whereBetween('dt_pub_date', array(date($tenDaysAgo->toDateTimeString()), date($currentDate->toDateTimeString())));
            })
            ->join(DB::raw($joinQry), function ($join) {
                $join->on("pCat.pk_i_id", "=", "t_category.fk_i_parent_id");
            })

            ->orderByRaw('RAND()')
            // ->order('dt_pub_date','desc')
            ->take(7)
            ->get();



ORIGINAL SQL WHERE EXISTS


SELECT *
FROM `items`
WHERE EXISTS
    (SELECT `items_city`.`id`
     FROM `items_city`
     WHERE items_city.item_id = items.id)
     
Laravel Eloquent Query with Update


  DB::table('contributions')
            ->whereStatusId(ContributionStatus::RECONCILED)
            ->whereNull('submission_id')
            ->whereExists(function ($query) {
                $query->select("declarations.id")
                    ->from('declarations')
                    ->whereRaw('declarations.id = contributions.declaration_id');
            })
            ->update([
                'submission_id' => $submission->id,
            ]);

Another exist implemenation

    
          $tenantUsers = User::whereHas('roles', function ($query) {
            $query->whereIn('roles.name', ['broker', 'manager', 'administrator']);
        })
            ->with(['roles' => function ($q) {
                $q->whereIn('roles.name', ['broker', 'manager', 'administrator'])
                    ->select('roles.id', 'roles.name');
            }])->where(function ($query) use ($search) {
                $query->where('email', 'LIKE', '%' . $search . '%')
                    ->orWhere(DB::raw("concat(first_name, ' ', last_name)"), 'LIKE', "%" . $search . "%")
                    ->orWhere('first_name', 'LIKE', '%' . $search . '%')
                    ->orWhere('last_name', 'LIKE', '%' . $search . '%');
            })->get(['id', 'first_name', 'last_name', 'email']);  


select 
  id, 
  first_name, 
  last_name, 
  email 
from 
  users 
where 
  exists (
    select 
      * 
    from 
      roles 
      inner join model_has_roles on roles.id = model_has_roles.role_id 
    where 
      users.id = model_has_roles.model_uuid 
      and model_has_roles.model_type = 'App\Models\Universal\User' 
      and roles.name in ('broker', 'manager', 'administrator') 
      and model_has_roles.team_id is null 
      and (roles.team_id is null or roles.team_id is null)
  ) 
  and (
    email LIKE '%dev%' 
    or concat(first_name, ' ', last_name) LIKE '%dev% '
    or first_name LIKE '%dev%' 
    or last_name LIKE '%dev%'
  ) 
  and users.deleted_at is null



Another exist implemenation
  
  
          return Contact::where('is_third_party', true)
            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->orWhere('mobile_number', 'LIKE', '%' . $search . '%')
                        ->orWhere('email_address', 'LIKE', '%' . $search . '%');
                });
            })->get();
            
            
        select 
          * 
        from 
          `contacts` 
        where 
          `is_third_party` = 1 
          and (
            `mobile_number` LIKE '%3%' or `email_address` LIKE '%3%'
          ) 
          and `contacts`.`deleted_at` is null

  
Another exist implemenation
  
  
$contacts = Contact::query()
            ->join('applications', 'applications.id', '=', 'contacts.application_id')
            ->join('users as brokers', 'brokers.id', '=', 'applications.broker_uuid')
            ->when($searchString, function ($query) use ($searchString) {
                //these where creates a parenthesis for the or
                $query->where(function ($query) use ($searchString) {
                    $query->where('contacts.first_name', 'like', '%' . $searchString . '%')
                        ->orWhere('contacts.last_name', 'like', '%' . $searchString . '%')
                        ->orWhere('contacts.email_address', 'like', '%' . $searchString . '%');
                });
            })
            ->when($brokerId, function ($query) use ($brokerId) {
                $query->where('applications.broker_uuid', $brokerId);
            })
            ->select(['contacts.*', 'brokers.first_name as  broker_first_name', 'brokers.last_name as broker_last_name']);
            

SELECT `contacts`.*,
       `brokers`.`first_name` AS `broker_first_name`,
       `brokers`.`last_name`  AS `broker_last_name`
FROM   `contacts`
       INNER JOIN `applications`
               ON `applications`.`id` = `contacts`.`application_id`
       INNER JOIN `users` AS `brokers`
               ON `brokers`.`id` = `applications`.`broker_uuid`
WHERE  ( `contacts`.`first_name` LIKE '%popo%'
          OR `contacts`.`last_name` LIKE '%popo%'
          OR `contacts`.`email_address` LIKE '%popo%' )
       AND `applications`.`broker_uuid` = '2bb75f31-8a87-443d-421a-3f21f4992322' 
       
  
Another exist implemenation
  
  
  here_here
  
Another exist implemenation
  
  
  here_here
  
Another exist implemenation
  
  
  here_here
  
Another exist implemenation
  
  
  here_here
  
Share:

Saturday, 21 April 2018

Understanding Laravel Return set

Difference between Laravel Eloquent, DB Raw, Json Encode and Json Decode result set. If you're using a DB:select raw command

$currencyRaw = DB::select( DB::raw('select * from currency));
It will give you a type array of objects in which you can display with -> command. The return set will be like this

array (
  0 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'EUR',
     's_name' => 'European Union euro',
     's_description' => 'Euro €',
     'b_enabled' => 1,
  )),
  1 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'GBP',
     's_name' => 'United Kingdom pound',
     's_description' => 'Pound £',
     'b_enabled' => 1,
  )),
  2 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'USD',
     's_name' => 'United States dollar',
     's_description' => 'Dollar US$',
     'b_enabled' => 1,
  )),
)  
If you're using a json_decode with FALSE parameter on eloquent object

        $currencyEloquent = Currency::all();
        $currencyJsonDecodeFalse  = json_decode(($currencyEloquent),false);
It will give you a type array of objects in which you can display with -> command. The return set will be like this

array (
  0 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'EUR',
     's_name' => 'European Union euro',
     's_description' => 'Euro €',
     'b_enabled' => true,
  )),
  1 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'GBP',
     's_name' => 'United Kingdom pound',
     's_description' => 'Pound £',
     'b_enabled' => true,
  )),
  2 => 
  stdClass::__set_state(array(
     'pk_c_code' => 'USD',
     's_name' => 'United States dollar',
     's_description' => 'Dollar US$',
     'b_enabled' => true,
  )),
)
If you're using a ->toArray on eloquent object

        $currencyEloquent = Currency::all();
        $currencyArray  = $currencyEloquent->toArray();
It will give you a type array with keys and values in which you can display with $currency['s_name']. The return set will be like this

array (
  0 => 
  array (
    'pk_c_code' => 'EUR',
    's_name' => 'European Union euro',
    's_description' => 'Euro €',
    'b_enabled' => true,
  ),
  1 => 
  array (
    'pk_c_code' => 'GBP',
    's_name' => 'United Kingdom pound',
    's_description' => 'Pound £',
    'b_enabled' => true,
  ),
  2 => 
  array (
    'pk_c_code' => 'USD',
    's_name' => 'United States dollar',
    's_description' => 'Dollar US$',
    'b_enabled' => true,
  ),
)  
If you're using a json_decode with TRUE parameter on eloquent object

        $currencyEloquent = Currency::all();
        $currencyJsonDecodeFalse  = json_decode(($currencyEloquent),true);
It will give you a type array with keys and value in which you can display with $currency['s_name'] command. The return set will be like this

array (
  0 => 
  array (
    'pk_c_code' => 'EUR',
    's_name' => 'European Union euro',
    's_description' => 'Euro €',
    'b_enabled' => true,
  ),
  1 => 
  array (
    'pk_c_code' => 'GBP',
    's_name' => 'United Kingdom pound',
    's_description' => 'Pound £',
    'b_enabled' => true,
  ),
  2 => 
  array (
    'pk_c_code' => 'USD',
    's_name' => 'United States dollar',
    's_description' => 'Dollar US$',
    'b_enabled' => true,
  ),
)  

Various ways to play with the return set of DB:RAW


        $sql = "select * from users";
        $keyUserIds = DB::select(DB::raw($sql));
        // $keyUserIds is an array of objects

        //converted to collection
        $collectionUserId = collect($keyUserIds);

        //to get columns
        $pluckedUserId = $collectionUserId->pluck('user_id');


        //Convert array of objects to array of ids only
        $user_ids = array_column($keyUserIds, 'user_id');
Share:

Monday, 12 March 2018

Laravel Seeding Example with Faker library

Install faker from https://github.com/fzaninotto/Faker

composer require fzaninotto/faker
From the command line

php artisan make:seeder UsersTableSeeder




use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
    }
}





use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(\App\User::class)->create([
            'email' => 'admin@admin.com',
            'password' => '123',
        ]);

        factory(\App\User::class, 100)->create();
    }
}

Share:

Saturday, 25 November 2017

Laravel Migrations Command Lines

I don't trust my memory well so I'll document some migrations command

php artisan make:migration add_paid_to_users --table="users"
This line will create a book table migrations

php artisan make:migration create_books_table --create="books"




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

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

This line will add a migration script to add author_id

php artisan make:migration add_author_id_to_book_table --table="books"


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

class AddAuthorIdToBookTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('books', function (Blueprint $table) {
            $table->integer('author_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('books', function (Blueprint $table) {
            //
        });
    }
}
My Template for creating migrations



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


class DifferentArtisanTypeForMySql extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create('my_table1', function (Blueprint $table) {
            $table->increments('id');

            $table->string('string_col');
            $table->string('string_col_with_length', 500);


            //create unsigned field which is the same type for field with increment attribute
            $table->unsignedInteger('unsigned_int_index')->index();
            //create string token with unique index
            $table->string('token', 100)->unique();


            $table->enum('enum_field', ['Beauty', 'Business service', 'Childrens products'])->nullable();


            $table->timestamp('timestamp_field')->nullable();
            $table->date('date_field')->nullable();
            $table->boolean('boolean_field')->default(0);

            //will create integer field with 11 in length
            $table->integer('integer_field')->default(0);

            //will create integer field with 10 in length
            $table->integer('unsigned_integer_field')->unsigned();
            
            $table->decimal('decimal_field', 6, 1)->nullable()->default(0);
            $table->tinyInteger('tinyint_field');
            $table->smallInteger('smallinteger_field')->nullable();

            $table->char('char_field', 2)->default('');
            $table->text('text_field');


        });



       // DB::statement('ALTER TABLE campaign_influencer_posts CHANGE COLUMN social_id account_id INT(11) NOT NULL ;');



        // Create table non auto increment field with index field
        Schema::create('my_table2', function ($table) {
            $table->integer('id')->unsigned()->index();
            $table->string('capital', 255)->nullable();
            $table->string('citizenship', 255)->nullable();

            $table->primary('id');
        });


        //Do you want to add a new records right away?
        Schema::create('my_table3', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->tinyInteger('active')->index();
        });

        DB::table('my_table3')->insert([
            'name' => 'Instagram',
            'active' => 1
        ]);

        DB::table('my_table3')->insert([
            'name' => 'Facebook',
            'active' => 1
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

        Schema::table('my_table1', function (Blueprint $table) {
            $table->dropColumn('string_col');
        });

       // DB::statement('ALTER TABLE campaign_influencer_posts CHANGE COLUMN account_id social_id INT(11) NOT NULL ;');


        Schema::dropIfExists('my_table1');
        Schema::dropIfExists('my_table2');
        Schema::dropIfExists('my_table3');    
    }

    
    //You might wish to rename some fields
    // but for laravel 5.X 
    // you need to run composer require doctrine/dbal

    public function up()
    {
        Schema::table('demographics', function (Blueprint $table) {
            $table->renameColumn('social_id', 'account_id');
        });

    }
   
}



Template for migration with foreign key


    public function up(): void
    {
        Schema::table('child_table', function (Blueprint $table) {
            $table->integer('foreign_column', false, true)->nullable()->after('column_name');
            $table->foreign('foreign_column')->references('id')->on('parent_table');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('child_table', function (Blueprint $table) {
            $table->dropForeign('foreign_key_here');
            $table->dropColumn('foreign_column');
        });
    }
Here are the list of data type columns that can be added https://laravel.com/docs/5.5/migrations#creating-columns
Share:

Monday, 6 November 2017

Using SQLite in Laravel Applications

 I have been playing with Laravel and MySQL just recently and I have been enjoying using it on one of my recent project.    It's an eCommerce system done with Laravel 5.3 with Paypal and Stripe Payment.  I have implemented a authorize and capture mechanism.   

I've been using MySQL for database which works as expected but my problem is I'm using 3 machines for my development.   I don't want to use any cloud database like AWS MySQL or Google cloud db, because it's a paid one and apparently I'm not online always.   Things like I can work even in train (really hardworking right?) wherein internet is superslow.

Now comes SQLite.   SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file.  Meaning a portable database which will solve my dillema.


To use SQLite on Laravel

Create a database laravel.sqlite file in the database folder of your laravel project.   You might need to download SQLite browser in http://sqlitebrowser.org/

/your-project/database/laravel.sqlite



Open your database.php file in the config folder of your project and make sure what you see in the image below is the same in your project.





'default' => env('DB_CONNECTION', 'sqlite'),


Go to your .env file and and change your DB_CONNECTION to
'sqlite'. Another thing you have to do is change DB_DATABASE to the path of your laravel.sqlite on your local computer.  You can leave the port, username and password.




DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=D://github/admin-dash/database/laravel.sqlite
DB_USERNAME=root
DB_PASSWORD=
Share:

Sunday, 5 November 2017

Laravel Default Env File Content

It is often helpful to have different configuration values based on
the environment where the application is running. For example, you
may wish to use a different cache driver locally than you do on your
production server.

To make this a cinch, Laravel utilizes the DotEnv PHP library by Vance
Lucas. In a fresh Laravel installation, the root directory of your application
will contain a .env.example file. If you install Laravel via Composer, this
file will automatically be renamed to .env. Otherwise, you should rename the
file manually.

Your .env file should not be committed to your application's source control,
since each developer / server using your application could require a different
environment configuration. Furthermore, this would be a security risk in the event
an intruder gain access to your source control repository, since any sensitive
credentials would get exposed.

If you are developing with a team, you may wish to continue including a .env.example
file with your application. By putting place-holder values in the example configuration
file, other developers on your team can clearly see which environment variables are
needed to run your application. You may also create a .env.testing file. This file will
override values from the .env file when running PHPUnit tests or executing Artisan commands
with the --env=testing option.



APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

.env for Laravel 8

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:9X1TB/g2Rx85u+8z+Dtm4FdSFX01BsOGs3fEJhJlrXU=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

To add paypal or stripe you can check Laravel eCommerce with Paypal and Stripe Payment
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.