Jumat, 02 Oktober 2020

Membuat fungsi global atau ServiceProvider AppServiceProvider Laravel

- contoh untuk convert translate :
> buatkan service providernya -> php artisan make:provider TranslateServiceProvider
    Isinya :
<?php

namespace App\Providers;

use App\Library\Services\Translate;
use Illuminate\Support\ServiceProvider;

class TranslateServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Library\Services\Translate', function ($app) {
          return new Translate("");
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

> Kalau belum ada folder Library\Services\ dibuatkan saja, dan sesuai diatas saya bukan class Translate di dalam folder service ini (Translate.php)
    Isinya :
<?php
namespace App\Library\Services;
use Stichoza\GoogleTranslate\GoogleTranslate;
  
class Translate
{
    public function translate($string)
    {
        $translate = new GoogleTranslate('en');

        return $translate->translate($string);
    }
}

> Setelah itu tambahkan/daftarkan service provider baru supaya terbaca disemua controller / global :
    edit di file config/app, line 'providers' : App\Providers\TranslateServiceProvider::class

> Untuk pemanggilan di setiap controller cukup seperti ini :
<?php

namespace App\Http\Controllers;

use App\Dokumen;
use App\Library\Services\Translate;

class DokumenHomeController extends Controller
{
    public function index(Translate $translate)
    {
        $dokumen_translate = $translate->translate("Param String yang dikirim untuk convert translate");

        return view('dokumen.index', $dokumen_translate);
    }
}

Sabtu, 15 Agustus 2020

Validasi Laravel (Laravel Validation)

 $this->validate($request, [

//validasi untuk cek form input string max 255 karakter

            'nama_kategori' => ['required', 'string', 'max:255'],

//validasi untuk cek form input number minimal 1 karakter

            'urutan' => ['required', 'numeric', 'min:1'],

        ]);

Kamis, 09 Juli 2020

laravel multi languange multi bahasa

- setting library untuk pemanggilan route :
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

- redirect setelah proses request :
return redirect(app()->getLocale() . '/home');

- action redirect dengan locale menggunakan redirect controller :
return Redirect::action('FaqController@index', app()->getLocale())->with('flash-success','Data Berhasil Diubah.');

- link url tambah locale bahasa :
<a href="{{URL::to(app()->getLocale(), 'faq/show/')}}"><i class="fa fa-eye"></i> Detail</a>|

- link dengan parameter tertentu :

blade : <a href="{{URL::to(app()->getLocale(),'faq/edit/'.$faq->id)}}"><i class="fa fa-pencil"></i> Edit</a>|

route :
Route::group(['prefix' => '{language}'], function () {
  Auth::routes();
  Route::put('faq/edit/{id_faq}', ['as' => 'edit', 'uses' => 'FaqController@update']);
});

controller :

public function edit($lang, $id)
    {
      $faq = Faq::findOrFail($id); 

      return view('admin.faq.edit', compact('faq'));
    }

- post data atau input data form harus menggunakan csrf token :
<form  action="{{URL::to(app()->getLocale(),'faq/create')}}" method="post">
         <input type="hidden" name="_token" value="{{ csrf_token() }}">
         <input type="text" name="alamat">
</form>

Selasa, 30 Juni 2020

tunning atau optimize server saat error 502 atau 504

Ubuntu :
- Cek nginx.conf besarkan countcurrent user
- Cek www.conf di php-fpm besarkan pm.max_children dan sesuaikan dengan kondisi server bisa dilihat di top atau plugin glances

service php7.3-fpm restart
service php7.3-fpm status
systemctl status nginx
systemctl restart nginx

Jumat, 19 Juni 2020

Fungsi fungsi laravel model

- multiple like atau cara menggunakan fungsi like dengan banyak kondisi :
$proposals = $this->where('is_submitted','=', $is_submit)
                      ->where(function($query) use ($keyword)
                            {
                              $query->where( 'judul','LIKE', '%'.$keyword.'%' )
                                    ->orWhere( 'nama_organisasi','LIKE', '%'.$keyword.'%' );
                            })
                  ->paginate(10);

- kondisi untuk query jika param tidak ada :
$query = $this->join('kategori_dokumens', 'kategori_dokumens.id', '=', 'dokumens.kategori_dokumen_id')
                    ->where('dokumens.active','=', true)
                    ->where(function($query) use ($param)
                          {
                            $query->where( 'dokumens.judul_dokumen','LIKE', '%'.$param['search'].'%' )
                                  ->orWhere( 'dokumens.deskripsi','LIKE', '%'.$param['search'].'%' );
                          });
      if (isset($param['kategori_dokumen'])) {
        $query->where('kategori_dokumens.slug_dokumen', $param['kategori_dokumen']);
      }
      
      $data = $query->paginate(3);
      return $data;

- limit query builder laravel :
$dokumen_latest_posts = Dokumen::whereActive(true)->orderBy('created_at', 'desc')->limit(3)->get();

- fungsi counting jumlah baris rows per bulan
$dokumens = \App\Dokumen::selectRaw('COUNT(*) as count, YEAR(created_at) year, DATE_FORMAT(created_at, "%M") month')
                                ->groupBy('year', 'month')
                                ->get();

Sabtu, 13 Juni 2020

Import restore data mysql secara parsial per kolom per tabel

Extracting a Table from a MySQL Dump

Occasionally, I need to use the data in a single table from a full MySQL database backup dump. Ordinarily, you’d just import the database dump into MySQL and go. Unfortunately, if the dump file is several Gigabytes (even when compressed), it becomes time-consuming to SCP this file around and then load it into MySQL.
In order to speed up the process, I extract the table I need from the full database dump. Then, I can take that table, SCP it to where I need it, load it into MySQL, and perform necessary operations with it. Fortunately, complicated programs and commands are not necessary for this: only grep and sed are needed.
The first step is to determine the table structure from the decompressed MySQL database dump:
BASH
$ grep -n "Table structure" [MySQL_dump_filename].sql
  • Example:
    Let’s say we want to extract the phpbb_config table from a giant MySQL phpBB database dump.
BASH
[kulesza@db ~]$ grep -n "Table structure" global_us_phpbb.sql
19:-- Table structure for table `ajax_chat_bans`
43:-- Table structure for table `ajax_chat_messages`
73:-- Table structure for table `ajax_chat_online`
100:-- Table structure for table `phpbb_acl_groups`
129:-- Table structure for table `phpbb_acl_options`
157:-- Table structure for table `phpbb_acl_roles`
186:-- Table structure for table `phpbb_acl_roles_data`
212:-- Table structure for table `phpbb_acl_users`
241:-- Table structure for table `phpbb_attachments`
283:-- Table structure for table `phpbb_banlist`
317:-- Table structure for table `phpbb_bbcodes`
349:-- Table structure for table `phpbb_bookmarks`
373:-- Table structure for table `phpbb_bots`
402:-- Table structure for table `phpbb_config`
428:-- Table structure for table `phpbb_confirm`
456:-- Table structure for table `phpbb_disallow`
  • This will provide you with the starting line number in the MySQL dump file which defines each table. Using this, determine the starting and ending line numbers of the table you need (the ending line number will be the starting line number of the next table, minus one).
The next step is to actually extract the table from the MySQL database dump file:
BASH
$ sed -n '[starting_line_number],[ending_line_number] p' [MySQL_dump_filename].sql > [table_output_filename].sql
  • Example:
    I extract the phpbb_config table into tmp.sql, and then use head to check that the SQL in the file is what I am expecting.
BASH
[kulesza@db ~]$ sed -n '402,427 p' global_us_phpbb.sql > tmp.sql
[kulesza@db ~]$ head tmp.sql 
-- Table structure for table `phpbb_config`
--
DROP TABLE IF EXISTS `phpbb_config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `phpbb_config` (
  `config_name` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',
  `config_value` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',
  `is_dynamic` tinyint(1) unsigned NOT NULL DEFAULT '0',
The last remaining step is to use the extracted table:
BASH
$ mysql -u root -p [some_database_name] < [table_output_filename].sql
  • Example: Now I load the phpbb_config table into a temporary MySQL database.
BASH
[kulesza@db ~]$ mysql -u root -p my_temp_database < tmp.sql
Note that these steps presume a decompressed, full MySQL database dump which contains table DROPCREATE, and INSERT SQL.

Minggu, 31 Mei 2020

mysql server

// https://www.shellhacks.com/mysql-show-users-privileges-passwords/
//melihat user dan host yang diizinkan
SELECT user,host FROM mysql.user;

//distinct atau grouping user berdasarkan username
SELECT DISTINCT user FROM mysql.user;

//update host user di mysql
UPDATE mysql.user SET Host='%' WHERE Host='localhost' AND User='username';

SELECT
-- *
JSON_EXTRACT(object_json_namakolomnya, "$.penyedia_id")
FROM
permohonan_pembaruan_staging
WHERE
permohonan_pembaruan_id = '4512';

//buat user dan bisa di remote menggunakan IP lokal Server
CREATE USER 'nama_usernya'@'%' IDENTIFIED BY 'passwordnya_apa';
GRANT ALL ON *.* TO 'nama_usernya'@'%';
FLUSH PRIVILEGES;

- membuat user mysql dan privilege nya
CREATE USER 'nama_user'@'192.168.ipnya' IDENTIFIED BY 'passXXXX';
GRANT ALL PRIVILEGES ON * . * TO 'nama_user'@'192.168.ipnya';
flush privileges;

- cara melihat whitelist server linux : sudo iptables -L -v -n | more

- import data menggunakan terminal server
mysql -u <username> -p <databasename> < <filename.sql>

Minggu, 17 Mei 2020

html

Beauty html (mengubah script html menjadi rapih) : https://www.freeformatter.com/html-formatter.html#ad-output

-> solusi select2 tidak muncul di modal box :
-hilang tabindex="-1" di class modal box (https://stackoverflow.com/questions/18487056/select2-doesnt-work-when-embedded-in-a-bootstrap-modal/33884094#33884094)

Rabu, 06 Mei 2020

Fungsi fungsi View Laravel

- untuk convert tanggal di form html dan php
<input type="text" name="tgl_awal_upload" class="form-control required single-daterange" value= "<?php echo date('d/m/Y', strtotime($kegiatan->tgl_awal_upload)); ?>">

- kondisi php untuk radiobutton
<div class='col-md-12'>
                      <label class="radio-inline">
                        <input type="radio" name="is_aktif" value="1"
                        <?php if ($kegiatan->is_aktif == 1): ?>
                          checked="checked"
                          <?php endif ?> > Aktif
                      </label>

                      <label class="radio-inline">
                        <input type="radio" name="is_aktif" value="0"
                        <?php if ($kegiatan->is_aktif == 0): ?>
                          checked="checked"
                          <?php endif ?> > Tidak Aktif
                      </label>
                    </div>

- cara memanggil extention file di view atau blade laravel :
<p class="size8 red lh2">File Path: {{ pathinfo($row->file_path, PATHINFO_EXTENSION)}}</p>
-> solusi select2 tidak muncul di modal box :

-> kondisi untuk input type radio get value dari db:
<div class="form-check"><label class="form-check-label"><input {{ ($dokumen->status_dokumen=='publish')? 'checked' : '' }} class="form-check-input" name="status_dokumen" type="radio" value="publish">Publish</label></div>
- render dengan membawa current url untuk search biasanya :
{!! $dokumens->appends(Request::except('page'))->render() !!}