Artisan tinker Error: In Configuration.php line 363: mkdir(): Permission denied

I got following error while running artisan tinker thru Google Compute VM console:

project@projectserver1:/var/www/html/Project_October$ php ./artisan tinker

In Configuration.php line 363:
 
mkdir(): Permission denied

And here is why and how to fix it:

This error occurs because you switch user (guessing using su) without “dash” option.

Replace su www-data with su - www-data and everything should works!

psysh tries to write runtime data in “original user” folder, instead of in “current user” folder…

PS my “current user” has XDG_RUNTIME_DIR env defined. Switching user without -, forced www-data to use the same env variable, while www-data hasn’t write permission in that folder.

Source: https://www.bountysource.com/issues/52403365-error-mkdir-permission-denied

 

 

Find out current requested Controller and Method Name on the Laravel

In years of development of project, it could be contains tons of features that consisted from hundred of controllers and thousand methods, it’s usually take time to specify where is current Controller name and Method name that is being requested by the browser  at the time,  here is the tip about how find it out:

dd(\Route::currentRouteAction());

put that line code somewhere in your base controller or middleware.

For 5.6

dd(class_basename(Route::current()->controller));

 

Laravel Migration Basic

In this post I gonna show a little bit about Laravel database migration

Install Laravel

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development 
╰─➤ laravel new DBMigration 
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file

Installed Laravel

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ php ./artisan 
Laravel Framework 5.6.15

Usage:
 command [options] [arguments]

Create an Setup SQLite Database

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ touch ./storage/database.sqlite && ls storage 
app database.sqlite framework logs

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ cat .env

APP_DEBUG=true
APP_URL=http://dbmigration.test:8181/
APP_KEY=LCG9E1xG5FQDMNauR8wWW3GTyB6Tj6Nv

DB_CONNECTION=sqlite
DB_DATABASE=storage/database.sqlite

Migrate  Migration Files that come with Laravel Instalation

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ ls database/migrations 
2014_10_12_000000_create_users_table.php 2014_10_12_100000_create_password_resets_table.php

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ php ./artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table

Migration Result

Selection_140.png

Migration Reset

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ php ./artisan migrate:reset 1 ↵
Rolling back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolling back: 2014_10_12_000000_create_users_table
Rolled back: 2014_10_12_000000_create_users_table

 

Compare Migrate and Reset Proses

╰─➤ php ./artisan migrate

2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table

 

╰─➤ php ./artisan migrate:reset

Rolling back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolling back: 2014_10_12_000000_create_users_table
Rolled back: 2014_10_12_000000_create_users_table

Migrate execution order

  1. Create users table
  2. Create password_resets table

Migration reset execution order

  1. Drop password_resets table
  2. Create users table

Conlusion: Reset and Rollback process are being executed in reversed order to avoid error.

Adding new column

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ vim ./database/migrations/2018_04_08_111208_add_address_to_users.php 1 ↵

--- Auto-Commands ---
╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ php ./artisan migrate 
Migrating: 2018_04_08_111208_add_address_to_users
Migrated: 2018_04_08_111208_add_address_to_users

 

Reset after Migrate

Selection_141.png

Rollback after Migrate (Reverse last migrate)

Selection_142.png

 

If you got following error while migration reset:

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ php ./artisan migrate:reset

Symfony\Component\Debug\Exception\FatalThrowableError : Class 'Doctrine\DBAL\Driver\PDOSqlite\Driver' not found

at /home/yoesoff/Development/DBMigration/vendor/laravel/framework/src/Illuminate/Database/SQLiteConnection.php:64
 60| * @return \Doctrine\DBAL\Driver\PDOSqlite\Driver
 61| */
 62| protected function getDoctrineDriver()
 63| {
 > 64| return new DoctrineDriver;
 65| }
 66| }
 67|

Exception trace:

1 Illuminate\Database\SQLiteConnection::getDoctrineDriver()
 /home/yoesoff/Development/DBMigration/vendor/laravel/framework/src/Illuminate/Database/Connection.php:884

2 Illuminate\Database\Connection::getDoctrineSchemaManager()
 /home/yoesoff/Development/DBMigration/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php:244

Please use the argument -v to see more details.

 

Here is the way  to fix it

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DBMigration 
╰─➤ composer require doctrine/dbal

Fix Error of Docker Compose up : port is already allocated

I got following errors after tried to run docker-compose up (later I realized that it was not an error but the service(s)/container(s) is already running )

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/Obunda_October ‹feature/First-Setup*› 
╰─➤ docker-compose up
Starting obundaoctober_obunda_october_1 ... 
Starting obundaoctober_obunda_october_1 ... error

ERROR: for obundaoctober_obunda_october_1 Cannot start service obunda_october: driver failed programming external connectivity on endpoint obundaoctober_obunda_october_1 (53c195720a02841c1a5c3f5c123af4b634d1ccbd9b42195dac3e4704f92574e0): Bind for 0.0.0.0:8181 failed: port is already allocated

ERROR: for obunda_october Cannot start service obunda_october: driver failed programming external connectivity on endpoint obundaoctober_obunda_october_1 (53c195720a02841c1a5c3f5c123af4b634d1ccbd9b42195dac3e4704f92574e0): Bind for 0.0.0.0:8181 failed: port is already allocated
ERROR: Encountered errors while bringing up the project.

This error occurred   because the container(s) is already up/running (usually because of auto start after the host booted) and used/locked the port(s).

If it’s happened to you just check the service and make sure that the service is already running or not, if the service already up that it means you no need to run docker-compose up again, but if you still want to use docker-compose up  then you have to stop all running container(s) that locked your port  by using following command:

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/Obunda_October ‹feature/First-Setup*› 
╰─➤ docker stop $(docker ps -a -q) 1 ↵
8ab72171abe9
4cfd47e550c8
0f18dad139dd
729c034697e4

 

And then try to execute docker-compose up again

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/Obunda_October ‹feature/First-Setup*› 
╰─➤ docker-compose up 
Starting obundaoctober_obunda_october_1 ... 
Starting obundaoctober_obunda_october_1 ... done
Attaching to obundaoctober_obunda_october_1
obunda_october_1 | Do not run Composer as root/super user! See https://getcomposer.org/root for details
obunda_october_1 | Loading composer repositories with package information
obunda_october_1 | Installing dependencies (including require-dev) from lock file
obunda_october_1 | Nothing to install or update
obunda_october_1 | Generating autoload files
obunda_october_1 | Laravel development server started: <http://0.0.0.0:8181>

 

Then the service is running at http://0.0.0.0:8181 as usual.

 

Setup Laravel 5.5 di OS Ubuntu 16.04

*Ini catatan pribadi bukan tutorial, tapi kalo mau nanya-nanya silahkan ke: mhyusufibrahim@gmail.com

Setup Laravel dengan menggunakan Docker containers adalah hal yang umum dilakukan saat ini dalam mengkonfigurasi lingkungan kerja (bahkan production) dalam pengembangan Web karena teknologi-teknologi tersebut hingga saat ini adalah hal yang masih cukup hangat untuk dibicarakan.

Saya akan mencoba belajar dengan tutorial ini dengan beberapa modifikasi.

Sebelum mulai ini detail env di laptop yang saya gunakan (Thinkpad X220)

╰─➤  docker -v; docker-compose -v; lsb_release -a

Docker version 17.12.1-ce, build 7390fc6

docker-compose version 1.17.0, build ac53b73

No LSB modules are available.

Distributor ID: Ubuntu

Description: Ubuntu 16.04.4 LTS

Release: 16.04

Codename: xenial

Bila anda belum punya Docker dan Docker Compose jangan lupa Install dulu.

 

Resolve DNS error dari dalam container

Container dalam host kita terkadang gagal untuk mengontak url-url yang diberikan karena DNS serve yang salah, contoh error adalah sebagai berikut:

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development 
╰─➤ docker run richarvey/nginx-php-fpm:1.4.1 ping www.google.com
ping: bad address 'www.google.com'

dan poin penting pertama adalah Konfigurasi DNS di Ubuntu yang baru adalah:

sudo vim /etc/docker/daemon.json

# Bukan lagi di: /etc/default/docker

Cara memperbaiki error terkait DNS ini:

  1. Cek DNS yang dipakai host Laptop kita:
  2. Masukan ke /etc/docker/daemon.json
  3. Restart servis Docker
Selection_117.png
seusaikan DNS di sudo vim /etc/docker/daemon.json supaya sama dengan hasil nmcli
 1 { 
 2 "dns": ["203.142.82.224", "182.253.236.236", "192.168.43.1"] 
 3 }

DNS Google, Telkom dan Tri

{
 "dns": ["8.8.8.8", "8.8.4.4", "203.142.82.224", "182.253.236.236", "1.1.1.1", "202.155.0.10", "202.155.0.15", "202.155.0.20", "202.155.0.25", "202.155.30.227", "10.0.18.38", "10.0.18.42"]
}

 

Siapkan DockerFile untuk membuat custom Image PHP7

DockerFile

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DREAMS-DBKL ‹development*›
 ╰─➤ vim Dockerfile
 1 FROM phpdockerio/php72-fpm 
 2 RUN apt-get update -y && apt-get install -y openssl zip unzip git
 3 #RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
 4 #RUN apt-get install pdo mbstring
 5 WORKDIR /app
 6 COPY . /app
 7 RUN composer install
 8
 9 CMD php artisan serve --host=0.0.0.0 --port=8181
 10 EXPOSE 8181

Kenapa Menggunakan phpdockerio/php72-fpm dari phpdocker.io ?

PHPDocker.io – PHP 7.2 / FPM container image

Ubuntu 16.04 PHP 7.2 FPM container image for PHPDocker.io projects. Packages are provided by Ondřej Surý.

Smaller in size than PHP’s official container (170MB vs 501MB) plus you don’t need to install any build dependencies let alone compile anything, Dotdeb already ship binaries for the vast majority, if not all, of PHP extensions available on PHP7.

Selection_094.png
Paling banyak di pull
Selection_095.png
PHP terbaru versi 7.2

 Jadinya saya pakai yang ini:

richarvey/nginx-php-fpm

Build Image

Selection_088.png

Penjelasan:

  1. docker build -t nx-php7-image .
    • Perintah untuk membuat Image berdasarkan konfigurasi DockerFile di currrent project folder.

Bila saat proses build terjadi error sbb: “Err:1 http://archive.ubuntu.com/ubuntu xenial InRelease” ikuti solusi ini. Bila tidak berhasil coba ganti network provider internet anda.

Selection_091.png
Ini adalah Image yang kita buat berdasarkan phpdockerio/php72-fpm

Running Image (Menjalankan Container)

Selection_087.png

Selection_089.png

Penjelasan:

  1. docker run -p 8181:8181 nx-php7-image
    • Menjalankan peruntah run untuk membuat container dari image nx-php7-image
    • bila ingin jalan dibelakang layar sebagai daemon tambahkan -d
      • docker run -d -p 8181:8181 nx-php7-image

Mematikan / Stop Running Container

Selection_086.png
Container yang sedang berjalan tidak bisa di stop dengan ctrl+c

Penjelasan:

  1. $ docker ps
    • Melihat active container dan mendapatkan ID nya, disini IDnya adalah: e37794a1c2e8
  2. $ docker container stop e37794a1c2e8
    • Mematikan container yang sedang berjalan
    • Ada banyak containers yang perlu dimatikan semua ?
      • docker kill $(docker ps -q)

Sampai disini kita mempelajari

  1. Mengenal DockerFile dan Syntaxnya.
  2. Membuild Image dari Image yang telah ada.
  3. Merunning container dari Image yang telah di build.
  4. Melihat available images dengan docker images
  5. Melihat running containers dengan docker ps
  6. Mematikan running container dengan  docker container stop ID-CONTAINER

abraham-lincoln-9382540-2-402

“Container(s) Adalah instance dari sebuah Image” 

– Abraham Lincoln 1809

Bonus stage, akses masuk ke dalam Container

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development 
╰─➤ docker exec -it <mycontainer> bash

Selection_093.png

Menyiapkan Image Oracle 12c

logo-oracle12

Kenapa pakai Image dari sath89/oracle-12c ?

Oracle Standard Edition 12c Release 1



Oracle Standard Edition 12c Release 1 on Ubuntu
This Dockerfile is a trusted build of Docker Registry.

Persiapan dan instalasi

Sumber referensi asal: https://github.com/MaksymBilenko/docker-oracle-12c

Pull image sath89/oracle-12c

Selection_098.png
docker pull sath89/oracle-12c

nobita

“Docker pull adalah proses mengambil image atau a repository dari sebuah registry”

– Nobita 2099

Jalankan Containers di Background

Selection_099.png

docker run -d -p 8080:8080 -p 1521:1521 sath89/oracle-12c

List of Running Containers

Selection_100.png
docker ps

Instalasi SQLPLUS (Sejenis dengan psql milik PostgreSQL)

Artikel yang mengulas SQLPLUS lebih dalam berbahasa Indonesia baca disini.

Selection_101.png
Uppsss! mari install dulu

SQL*Plus Overview

SQL*Plus is an interactive and batch query tool that is installed with every Oracle Database installation. It has a command-line user interface, a Windows Graphical User Interface (GUI) and the iSQL*Plus web-based user interface.

There is also the SQL*Plus Instant Client which is a stand-alone command-line interface available on platforms that support the OCI Instant Client. SQL*Plus Instant Client connects to any available Oracle database, but does not require its own Oracle database installation. See the Oracle Call Interface Programmer’s Guide for more information on the OCI Instant Client.

Download RPMs files di http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.htmlSelection_102.png

Ikuti cara ini untuk install di Ubuntu atau ini yang lebih jelas.

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Downloads  

╰─➤  sudo alien -i oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64.rpm 

dpkg --no-force-overwrite -i oracle-instantclient12.2-basic_12.2.0.1.0-2_amd64.debSelecting previously unselected package oracle-instantclient12.2-basic.(Reading database ... 293364 files and directories currently installed.)Preparing to unpack oracle-instantclient12.2-basic_12.2.0.1.0-2_amd64.deb ...Unpacking oracle-instantclient12.2-basic (12.2.0.1.0-2) ...Setting up oracle-instantclient12.2-basic (12.2.0.1.0-2) ...Processing triggers for libc-bin (2.23-0ubuntu10) ...

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Downloads  

╰─➤  sudo alien -i oracle-instantclient12.2-devel-12.2.0.1.0-1.x86_64.rpm  

dpkg --no-force-overwrite -i oracle-instantclient12.2-devel_12.2.0.1.0-2_amd64.debSelecting previously unselected package oracle-instantclient12.2-devel.(Reading database ... 293386 files and directories currently installed.)Preparing to unpack oracle-instantclient12.2-devel_12.2.0.1.0-2_amd64.deb ...Unpacking oracle-instantclient12.2-devel (12.2.0.1.0-2) ...Setting up oracle-instantclient12.2-devel (12.2.0.1.0-2) ...

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Downloads  

╰─➤  sudo alien -i oracle-instantclient12.2-sqlplus-12.2.0.1.0-1.x86_64.rpm  

dpkg --no-force-overwrite -i oracle-instantclient12.2-sqlplus_12.2.0.1.0-2_amd64.debSelecting previously unselected package oracle-instantclient12.2-sqlplus.(Reading database ... 293441 files and directories currently installed.)Preparing to unpack oracle-instantclient12.2-sqlplus_12.2.0.1.0-2_amd64.deb ...Unpacking oracle-instantclient12.2-sqlplus (12.2.0.1.0-2) ...Setting up oracle-instantclient12.2-sqlplus (12.2.0.1.0-2) ...

Konfigurasi hingga akhrinya sqlplus64 jalan

Selection_103.png
sudo ldconfig &&  . ~/.zshrc

Login ke database dengan SQLPLUS

Selection_104.png
system/oracle@//localhost:1521/xe

Instal Oracle SQL Developer

Nah, kalau SQLPLUS adalg versi console di terminal maka Oracle SQL Developer adalah versi desktopnya.

Download Oracle SQL Developer disini.

Pilih yang RPM supaya bisa di insall dengan menggunakan Alien.

Linux RPM

(4e0156dd0edf4ecfc8d65c989ebf548a)
Installation NotesJDK 8 or above require

Perintah instalasi Oracle Developer Studio

sudo alien -i --scripts sqldeveloper-17.4.1.054.0712-1.noarch.rpm

Selection_105.png

Hasil instalasi

Selection_106.png

Selection_107.png

Setting Koneksi ke database yang berada didalam kontainer

hostname: localhost
port: 1521
sid: xe
service name: xe
username: system
password: oracle
Selection_108.png

Koneksi dari Oracle SQL Developer ke Oracle DB 12c yang berada di Container

Sampai disini kita mempelajari hal lain yaitu:

  1. Pull image dan menjalankan container Oracle DB 12c.
  2. Menginstal dan login ke SQLPLUS di console terminal.
  3. Mengistall GUI Buat Oracle 12c yaitu Oracle SQL Developer

Jadi Sampai disini kita sudah memiliki beberapa hal penting:

  1. Container yang berisi PHP7 (Dengan custom Image)
  2. Container yang berisi Oracle 12c
  3. SQLPLUS Oracle SQL Developer

Selanjutnya mari setup docker compose…!

 

Docker Compose

spongebob-squarepants
“Compose is a tool for defining and running multi-container Docker applications. ” Spongebob

Docker Compose

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a Compose file to configure your application’s services. Then, using a single command, you create and start all the services from your configuration.

Mau tau lebih banyak tentang docker-compose ? baca aja ini dan ini.

Mari kita mulai dengan memastikan Docker Compose itu sendiri sudah ada di Laptop atau PC kita:

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/TestAja ‹development*› 
╰─➤ docker-compose -v
docker-compose version 1.17.0, build ac53b73

Masuk Ke Project Folder

Selection_110.png
Lihat, error diatas menyuruh kita menyiapkan file docker-compose.yml

Membuat file docker-compose.yml (Sejajar folder app)

Selection_111.png
Image yang dipakai nx-php7 (Build ulang aja yang sebelumnya nx-php7-image jadi nx-php7)
Selection_112.png
docker-compose up (matikan: docker-compose stop)

Dockerfile

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DREAMS-DBKL ‹development*› 
╰─➤ ccat Dockerfile 
FROM phpdockerio/php72-fpm

# https://medium.com/@shakyShane/laravel-docker-part-2-preparing-for-production-9c6a024e9797 
COPY . /var/www
WORKDIR /var/www

# Do not execute composer as root
# RUN useradd -ms /bin/bash phpguy
# set phpguy as sudoer
# RUN adduser phpguy sudo
# switch current user
# USER phpguy
# *Docker root is not Host's root, so it's ok to root inside container CMIIW
# RUN composer install

# better way to run composer: https://stackoverflow.com/questions/46786589/running-composer-install-within-a-dockerfile
CMD bash -c "composer install && php artisan serve --host=0.0.0.0 --port=8181"
#CMD bash -c "composer install"

EXPOSE 80

 

Docker Compose File

╭─yoesoff@yoesoff-ThinkPad-X220 ~/Development/DREAMS-DBKL ‹development*› 
╰─➤ ccat docker-compose.yml 
version: '3.2'
services:
 database:
 image: sath89/oracle-12c
 ports: 
   - "1521:1521" 
   - "8080:8080" 
 restart: always

dream_dbkl:
 depends_on:
 - database
 build: 
 context: .
 dockerfile: ./Dockerfile
 ports:
 - "8181:8181"
 restart: always
 environment:
 DATABASE_PORT: "1521"
 DATABASE_SID: xe
 DATABASE_SERVICE_NAME: xe
 DATABASE_USERNAME: system 
 DATABASE_PASSWORD: oracle
 DATABASE_NAME: dreams

Selanjutnya

docker-compose build # up juga include build kalo belum
# Lalu
docker-compose up
# lalu 
docker run sath89/oracle-12c /entrypoint.sh

 

 

Bila ada errors saat docker-compose build hapus caches:

$ docker-compose rm

Containers dengan Docker Compose

Selection_126.png

 

Bonus Stage

Cara Stop dan Menghapus semua containers

  1. Melihat semua containers yang ada: docker ps -s
  2. Melihat containers yang aktif: docker ps
  3. Stop semua containers:  docker stop $(docker ps -a -q)
  4. Remove semua containers:  docker rm $(docker ps -a -q)
  5. 3 dan 4 hanya mau eksekusi yang running saja ? remove -a
Selection_115.png
Container hanya di stop
Selection_116.png
Containers di remove

Dari berbagai sumber

https://buddy.works/guides/laravel-in-docker

View at Medium.com

https://hub.docker.com/r/phpdockerio/php72-fpm/~/dockerfile/

https://hub.docker.com/r/sath89/oracle-12c/

https://codediary.net/posts/install-sqlplus-on-ubuntu-16-04/

https://askubuntu.com/questions/159939/how-to-install-sqlplus

https://stackoverflow.com/questions/41928566/installing-oracle-datamodeler-on-ubuntu-16-04/43524386

https://linuxhint.com/docker-compose-tutorial/

https://askubuntu.com/questions/170640/how-to-disable-apache2-server-from-auto-starting-on-boot (disable host running service)

Troubleshoting

https://github.com/gliderlabs/docker-alpine/issues/183

https://odino.org/cannot-connect-to-the-internet-from-your-docker-containers/

https://unix.stackexchange.com/questions/28941/what-dns-servers-am-i-using Check my DNS

https://askubuntu.com/questions/475764/docker-io-dns-doesnt-work-its-trying-to-use-8-8-8-8 Resolved my DNS error

 

 

 

 

Catatan Membuat Guestbook dengan Laravel 5.5 dan VueJS

Ini hanya catatan personal bukan tutorial!

Pada postingan ini saya membuat catatan untuk memudahkan kembali saya mengingat-ingat apa yang telah saya lakukan dan saya pelajari. Kali ini saya mencoba mempelajari Laravel 5.5 LTS dengan VueJS (Laravel+Vue saya lihat sebagai sebuah pasangan serasi untuk web development modern saat ini).

Catatan ini sendiri tidak akan ada banyak tulisan karena proses instalasi  Laravel dan VueJS sendiri berada di artikel lain yang terpisah yaitu Larastart yang sebelumnya telah saya buat (Artikel catatan tentang Larastart ini cukup panjang dan tidak begitu rapih).

Mari kita mulai mencatat dengan snapshot:

Tahap 1. Generate Model dan Migration

3.Generate-Model-dan-Migration
php artisan make:model Guestbook/Signature -m

Ketika menyertakan -m  mala akan memberikan tanda pada command untuk juga menggenerate migration untuk kita, hal ini membantu kita menghemat banyak waktu.

Edit dan sesuaikan App\Guestbook\Signature.php dan database/migrations/2018_03_03_032608_create_signatures_table.php (cek di github project ini).

Tahap 2. Generate Model Factory

4.Factory.png
php artisan make:factory SignatureFactory

Setelah Factory digenerate gunakan Faker untuk memproduksi data Dummy/Fake yang akan kita gunakan selama testing.

5.faker
database/factories/SignatureFactory.php

Membuat seeder supaya dummy data bisa digenerate saat provisioning Vagrant / Docker.

6.seeder-generate.png

Tahap 3. Generate Controllers

Generate 2 Files Controllers sebagai berikut:

  1. php artisan make:controller Api/V1/Guestbook/SignatureController
  2. php artisan make:controller Api/V1/Guestbook/ReportSignature

7.set-COntrollers.png

8.generated-controller

Tahap 4. Generate Transformer

8.Resource-Signature-transformer.png

Tahap 5. Siapkan Halaman Utama

Generate Controller untuk view

╭─yusuf@yusuf-he ~/htdocs/Larastarter ‹master*›
╰─➤ ./artisan make:controller Guestbook/SignatureController
Controller created successfully.

10.controoler-view

Create HTML view

11.guest-book-index.png

13.routes-only

 

Sumber: Link

Laravel join table with same fields name

Join table in Laravel is easy but if you don’t specified the table fields that want to be use/select it will be cause wrong data, here is my simple solution:


$quiz_responses
->leftJoin('users', 'quiz_responses.user_id', '=', 'users.id')
->leftJoin('students', function ($join) {
$join->where('users.personable_type', '=', 'Student');
$join->on('users.personable_id', '=', 'students.id');
})
->where('students.is_viewer', '', true) // jangan tampilkan viewer bila bukan viewer
->select(DB::raw('quiz_responses.*')); // hindari bentrok field

I joined the users and students tables for filtering purpose, no need to be shown in the view so the best way to avoid unwanted error is by make sure that the only table that being viewed is `quiz_responses` using following code:


//......

->select(DB::raw('quiz_responses.*')); // hindari bentrok field

//......

Laravel PHPUnit: Check form submit redirection

I just made a Laravel  UnitTest to test and make sure that my create function is working and redirects user to the right url after form post submitted , this is how I make it work:


public function testSurveysCreateSuccess()
    {
        $form = [
            'name' => 'New Survey',
            'type' => 'Lecturer',
            'description' => 'It\'s a text'
        ];

        $url =  '/admin/courses/'.$this->course->id.'/surveys';

        $response = $this->actingAs($this->user)->call('POST', $url, $form);
        $this->assertEquals(302, $response->status());
        $redirect_to = $response->getTargetUrl();

        $this->assertEquals($redirect_to, $this->baseUrl.$url);
    }

Task Scheduling using Laravel 5

In this blog post I will show you an easy example about how to create a simple Laravel 5 Command-Line program to be executed regularly by particular time interval or specified time.

Laravel’s command scheduler allows you to fluently and expressively define your command schedule within Laravel itself. When using the scheduler, only a single Cron entry is needed on your server. Your task schedule is defined in the app/Console/Kernel.php file’s schedule method. To help you get started, a simple example is defined within the method.

Create Simple Laravel Command-Line

we will use two log files to store output text (I show you my real path to avoid confuse ) :

Cron log file :  /home/yusuf/general.log

Scheduler output file: /home/yusuf/htdocs/blog/storage/logs/scheduler.log

 

  • Create app/Console/Commands/SayHello.php.

    1. CreateSayHelloDotPHP
    Create a new PHP file
  • Let’s write the simple short php code

    vim app/Console/Commands/SayHello.php

    namespace App\Console\Commands;
    
      use Illuminate\Console\Command;
    
      class SayHello extends Command
      {
          protected $signature = 'sayhello';
          protected $description = 'Say Hello User';
    
          public function __construct()
          {
              parent::__construct();
          }
    
          public function handle()
          {
              $this->info('Hello user...! ('. date("Y-m-d H:i:s") .') ');
          }
      }
    

    vim app/Console/Commands/Kernel.php

     /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
     protected $commands = [
         Commands\SayHello::class
     ];
    
  • Check out the new registered Laravel 5 Command-Line in the command list

    3. checkNewCommand
    New registered Laravel Command-line
  • Execute SayHello as Laravel 5 Command-Line program

    4. ExecuteIt
    Execute command line on terminal

Create Scheduler to Execute Command-Line

The next important step is about how to execute our Laravel Command-Line regularly. By using the Laravel scheduler you only need to add the following short line Cron entry to your server an then Laravel Forge will manage the Cron entries for you:

  • Create a log file for our Laravel scheduler storage/logs/scheduler.log:5. Laravel-Logs
  • Edit app/Console/Commands/Kernel.php   

    vim app/Console/Commands/Kernel.php

  • /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
     protected function schedule(Schedule $schedule)
     {
         $filePath = '/home/yusuf/htdocs/blog/storage/logs/scheduler.log';
         $schedule->command('sayhello')->everyMinute()->sendOutputTo($filePath);
     }
    
  • Test execute the scheduler

    ./artisan schedule:run6.scheduler-registered

  • Register schedule command as cron entry

    $ crontab -e7.registerCronEntry.png

     

    CronTabBlog1

  • Save the file and quit text editor
  • Tail the log file to see the result

    tail -f ~/general.log

    tail -f /home/yusuf/htdocs/blog/storage/logs/scheduler.log

    CrontabOutput2

  • That’s all