Laraveler


Membuat Aplikasi Laravel 5 MVC Dasar

Aplikasi Laravel mengikuti pola desain Model-View-Controller tradisional , di mana Anda menggunakan:

✓ Controller untuk menangani permintaan pengguna dan mengambil data, dengan memanfaatkan Model
✓ Model untuk berinteraksi dengan database Anda dan mengambil informasi objek Anda
✓ View untuk merender halaman

Permintaan dibuat - misalnya, ketika pengguna memasukkan URL yang terkait dengan aplikasi Anda.
Sebuah rute yang berhubungan dengan URL yang memetakan URL untuk aksi kontroler.
Itu kontroler tindakan memanfaatkan diperlukan Model (s) untuk mengambil informasi dari database, dan kemudian melewati data yang off untuk tampilan.
Dan pandangan itu menampilkan halaman akhir.

Saya suka mengatakan bahwa aplikasi MVC sangat mirip bermain dengan Lego .

Dan membangun satu menggunakan Laravel 5 sangat mudah.

Membangun aplikasi sampel
Demi demonstrasi, saya akan memandu Anda melalui proses pembuatan awal contoh aplikasi Laravel 5 dengan semua komponen MVC - model, tampilan, dan pengontrol.

Jadi, katakanlah Anda ingin membuat aplikasi yang berhubungan dengan mobil ...

Model

Kami akan mulai dengan membuat model, untuk mewakili Mobil.

Laravel hadir dengan antarmuka baris perintah yang fantastis, built-in, CLI Tukang , yang menyediakan Anda dengan banyak perintah yang berguna untuk membantu Anda membangun aplikasi Anda.

Jadi, jalankan baris perintah Anda (dan hubungkan ke mesin virtual Homestead Anda, jika Anda menggunakan Laravel Homestead ), masuk ke direktori utama aplikasi Anda, dan jalankan perintah berikut untuk membuat model Mobil baru:

php artisan make:model Car --migration


Semua model disimpan di appdirektori utama , sehingga perintah tersebut akan menghasilkan app/Car.php file model dengan kode berikut:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    //
}

Karena fungsi model bawaan Laravel, hanya dengan membuat kelas model kosong, Laravel akan berasumsi bahwa model ini dikaitkan dengan tabel database bernama cars.

Dan, sebenarnya, dengan menyediakan --migrationopsi itu ketika membuat model, Laravel juga menghasilkan file migrasi database untuk membuat carstabel basis data itu. File migrasi terletak di [timestamp]_create_cars_table.phpdan berisi kode berikut:

<?php



use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;



class CreateCarsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('cars', function (Blueprint $table) {

            $table->increments('id');

            $table->timestamps();

        });

    }



    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::drop('cars');

    }

}


(Jika Anda tidak terbiasa dengan konsep migrasi basis data, baca lebih lanjut tentang bagaimana Laravel menggunakan migrasi basis data untuk membantu Anda mengelola basis data Anda langsung dari dalam aplikasi Anda. Luar biasa.)

Yang harus Anda lakukan sekarang adalah menggunakan dokumentasi pembangun Skema Laravel untuk menyelesaikan file migrasi. Jadi Anda dapat menentukan beberapa kolom tambahan untuk, katakanlah, menyimpan pembuatan mobil, model, dan tanggal produksi:

  Schema::create('cars', function (Blueprint $table) {

    $table->increments('id');

    $table->string('make');

    $table->string('model');

    $table->date('produced_on');

    $table->timestamps();

  });


  Lalu Anda dapat menjalankan migrasi untuk membuat carstabel menggunakan perintah Artisan berikut:

 
php artisan migrate


  Dengan item yang berhubungan dengan basis data yang dialamatkan, kita sekarang dapat melanjutkan untuk membuat pengontrol.

  Catatan: Demi pengujian, pada titik ini, saya hanya secara manual menambahkan entri ke carstabel database.


Controller
Di Laravel, sejenis objek - seperti Mobil, dalam hal ini - disebut sebagai sumber daya .

Karena ini sangat umum untuk membangun aplikasi di sekitar sumber daya, Anda dapat membuat pengontrol sumber daya - pengontrol untuk menangani semua permintaan yang terkait dengan sumber daya - menggunakan perintah Artisan sederhana lain:

php artisan make:controller CarController


Itu akan menghasilkan app/Http/Controllers/CarController.phpfile controller dengan kode berikut:

<?php



namespace App\Http\Controllers;



use Illuminate\Http\Request;



use App\Http\Requests;

use App\Http\Controllers\Controller;



class CarController extends Controller

{

    /**

     * Display a listing of the resource.

     *

     * @return Response

     */

    public function index()

    {

        //

    }



    /**

     * Show the form for creating a new resource.

     *

     * @return Response

     */

    public function create()

    {

        //

    }



    /**

     * Store a newly created resource in storage.

     *

     * @return Response

     */

    public function store()

    {

        //

    }



    /**

     * Display the specified resource.

     *

     * @param  int  $id

     * @return Response

     */

    public function show($id)

    {

        //

    }



    /**

     * Show the form for editing the specified resource.

     *

     * @param  int  $id

     * @return Response

     */

    public function edit($id)

    {

        //

    }



    /**

     * Update the specified resource in storage.

     *

     * @param  int  $id

     * @return Response

     */

    public function update($id)

    {

        //

    }



    /**

     * Remove the specified resource from storage.

     *

     * @param  int  $id

     * @return Response

     */

    public function destroy($id)

    {

        //

    }

}



Perhatikan bahwa secara otomatis menghasilkan pengontrol dengan semua tindakan CRUD yang khas.

Sekarang, kita hanya perlu menentukan rute untuk menghubungkan URL dengan semua tindakan pengontrol ini.

Rute
Sekali lagi, karena ini adalah skenario umum, Anda dapat menentukan rute sumber daya tunggal , yang membuat rute untuk semua tindakan pengontrol sumber daya tersebut.

Di file konfigurasi rute - app/Http/routes.php- tambahkan yang berikut untuk menentukan rute sumber daya Mobil:

Route::resource('cars', 'CarController');


Definisi rute tunggal itu akan menentukan semua rute yang terkait dengan sumber daya Mobil kami:



Request Type Path Action Route Name
GET /cars index cars.index
GET /cars/create create cars.create
POST /cars store cars.store
GET /cars/{car} show cars.show
GET /cars/{car}/edit edit cars.edit
PUT/PATCH /cars/{car} update cars.update
DELETE /cars/{car} destroy cars.destroy


Sekarang, demi contoh, mari selesaikan implementasi halaman Show Car.

Controller ini showtindakan
Sesuai tabel sebelumnya, halaman Show Car akan dapat diakses http://app.url/cars/{car}. Dalam hal ini, {car}kehendak, pada kenyataannya, menjadi idobjek mobil dalam database.

Jadi, misalnya, URL untuk melihat mobil dengan iddari 1akan http://app.url/cars/1.

Untuk mengimplementasikan halaman Show Car, dalam aksi pengontrol show, kita perlu:

Gunakan Carmodel untuk mengambil objek Mobil yang ditunjuk dari database.
Muat tampilan untuk halaman Show Car, dan berikan objek Mobil yang diambil dari database.
Pertama, untuk mengakses model Mobil di controller, kita perlu menambahkan usepernyataan baru di atas kelas pengontrol:

.

.

.

use App\Car;



class CarController extends Controller

{

.

.

.

Kemudian, kita dapat menyelesaikan showtindakan dengan kode berikut:

.

.

.

    public function show($id)

    {

      $car = Car::find($id);

      return view('cars.show', array('car' => $car));

    }

.

.

.

Ketika kami mengunjungi URL mobil 1 - http://app.url/cars/1- Laravel membuat 1URL di dapat diakses melalui $idvariabel dalam showfungsi, yang ditunjukkan di atas.

Dan mengambil objek mobil menggunakan Carmodel semudah memanggil Car::finddan melewati itu $id.

Tampilan kemudian dimuat menggunakan viewfungsi dan meneruskan nama tampilan (yang akan kita buat dalam satu menit) dan array dengan data yang akan diberikan ke tampilan.

Terakhir, kita perlu membuat tampilan pertunjukan.

Tampilan dan Melengkapi Halaman
File tampilan LARAVEL semuanya disimpan dalam resources/viewsfolder. Dan mereka dapat diatur menjadi subfolder dalam direktori itu.

Pada langkah sebelumnya, kami meneruskan viewfungsi nama tampilan cars.show. Itu memberitahu Laravel untuk mencari file tampilan yang terletak di subfolder bernama cars(dalam resources/viewsdirektori utama ) bernama show.blade.php.

File tampilan Laravel menggunakan mesin templat Blade , dan karenanya diberi nama .blade.php.

Jadi, untuk menyelesaikan implementasi halaman Show Car ini, kita bisa membuat resources/views/cars/show.blade.phpfile tampilan dengan kode berikut:

<!DOCTYPE html>

<html>

  <head>

    <title>Car {{ $car->id }}</title>

  </head>

  <body>

    <h1>Car {{ $car->id }}</h1>

    <ul>

      <li>Make: {{ $car->make }}</li>

      <li>Model: {{ $car->model }}</li>

      <li>Produced on: {{ $car->produced_on }}</li>

    </ul>

  </body>

</html>


Karena kami mengirimkan Carobjek ke tampilan - kembali ke showtindakan pengontrol - dengan tombol array car, kita dapat mengaksesnya dalam tampilan melalui variabel dengan nama yang sama $car,.

Objek diambil melalui model adalah contoh dari kelas model itu.

Dan, seperti yang Anda lihat, nilai Carobjek dapat diakses menggunakan nama yang sama dengan nama carskolom tabel database terkait .

Akhirnya, Anda melihat penggunaan sintaks Blade untuk mencetak informasi. Berikut ini, misalnya, mencetak make mobil:

{{ $car->make }}

Pernyataan itu hanya diterjemahkan ke dalam echopernyataan PHP murni di latar belakang:

<?php echo $car->make; ?>

Tetapi sintaks Blade membuat tampilan tulisan lebih cepat dan lebih menyenangkan, dan membacanya jauh lebih mudah.

Permulaan Aplikasi Web MVC hanya dalam 10 Menit
Dan begitulah!

Begitulah cara cepat, dan mudah, Anda dapat membangun aplikasi web MVC menggunakan Laravel 5.

Dengan kombinasi perintah CLI Artisan dan fungsi built-in yang disediakan, membuat aplikasi Laravel cepat dan menyenangkan.
Read more »

Bagaimana cara Custom Login dengan Memodifikasi Auth Laravel 5.3

Ada banyak kelebihan yang didapatkan ketika membuat sendiri fitur login dari awal. Seperti alur kerja aplikasi yang bebas diatur sedemikian rupa. Namun, ketika menggunakan auth yang sudah disediakan, khususnya fitur login, bukan berarti kita terpaku pada alur yang sudah dibuat Laravel. Dengan menggunakan auth bawaan Laravel, kita juga dimungkinkan membuat fitur login dengan spesifikasi khusus.

Contoh kasus pada tulisan ini dapat diimplementasikan pada Laravel versi 5.3 ke atas.

Jika kita buka controller login yang terletak dalam berkas app/Http/Controllers/Auth/LoginController.php, akan terlihat hanya ada satu method di dalam class tersebut, itupun method constructor. Dalam class controller ini, tidak didefinisikan secara eksplisit fungsi untuk menangani proses login.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Jika diperhatikan, class controller di atas mengimpor dan menggunakan trait AuthenticatesUsers yang terletak dalam berkas berikut:

vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php

Nah, di dalam trait tersebutlah method yang berhubungan dengan fungsi login didefinisikan. Method yang tersedia lengkap mulai dari menampilkan formulir login, validasi, pengecekan user, sampai dengan respons. Setiap proses dipisah ke dalam method tersendiri. Hal ini memungkinkan pemrogram (programmer) untuk mengubah hal yang dirasa perlu saja.

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = [$this->username() => trans('auth.failed')];

        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'email';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }
}

***

Sebagai contoh permulaan, kita punya kasus untuk mengubah path lokasi view login yang secara bawaan merujuk ke “auth.login”, kemudian diubah menjadi “user.login”.

Untuk memodifikasi path tersebut, tentunya tidak dianjurkan mengubah langsung pada trait. Alih-alih melakukan perubahan pada trait AuthenticatesUsers, kita dapat menimpanya method tersebut sesuai dengan konsep trait di PHP.

Dalam trait, method untuk menampilkan form login bernama showLoginForm(). Untuk menimpa atau mengabaikan method ini dalam trait, kita hanya perlu menambahkan nama method yang sama ke dalam class LoginController.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('user.login');
    }
}

Voila! Path formulir login sudah diubah sesuai dengan contoh kasus pertama. Tentunya, kita juga dapat menambahkan variabel pada view layaknya controller yang sering kita buat sebelumnya.

***

Contoh kedua misalnya, kita akan menambahkan validasi di formulir login yang sebelumnya hanya mengecek email dan password, maka di custom login yang kita buat juga akan melakukan pengecekan kode unik.

Dalam trait, method untuk memvalidasi input dari pengguna bernama validateLogin(). Salin method ini ke dalam LoginController, dan tambahkan validasi kode unique sesuai dengan spesifikasi contoh kasus.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
     */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('user.login');
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
            'code' => 'required|exists|users,code',
        ]);
    }
}

***

Nah, sampai di sini, kita sudah berhasil memodifikasi dua hal, yaitu path formulir login dan validasi input tambahan.

Sekarang, masuk ke contoh lainnya, yang mana selain input email dan password, sistem juga harus mengecek status user apakah sudah aktif atau belum. Di dalam pangkalan data, kalian menyimpan data “A” sebagai penanda status user sudah aktif.

Facade Auth di Laravel sudah menyediakan data kombinasi selain email dan password. Sebagai contoh, untuk mengecek credential user, kalian bisa menuliskan skrip seperti di bawah.

$loggedIn = \Auth::attempt([
    'email' => $request->email,
    'password' => $request->password,
    'status' => 'A',
], $remember);

Setiap kali ingin menambahkan kombinasi pengecekan, kalian cukup mendefinisikannya pada argumen pertama method attempt() dalam facade Auth.

Di trait AuthenticateUsers, penulisan skripnya sedikit berbeda walau pada dasarnya menggunakan package yang sama. Sebelum memodifikasinya, terlebih dahulu kita lihat isi method attemptLogin() yang sudah ada.

/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

Method attemptLogin() juga terikat dependensi dengan method lain yang bernama credentials(). Method ini berfungsi untuk mengambil request apa saja yang dimasukkan oleh pengguna. Secara bawaan, hanya email dan password yang diizinkan untuk digunakan.

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password');
}

Untuk memodifikasinya, hal pertama yang dilakukan adalah menambahkan izin untuk request yang bernama “status” (dengan asumsi nama kolom di pangkalan data juga “status”).

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password', 'status');
}

Langkah selanjutnya, definisikan status harus bernilai “A”. Karena pengecekan status ini bukan berasal dari masukan data user, maka kita dapat menambahkan nilai pada object $request dengan method merge().

/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    $request->merge(['status' => 'A']);

    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

Sebagai alternatif penggunaan method merge(), kalian juga dapat menggunakan method add() seperti yang dicontohkan oleh Laravel Daily.

$request->request->add(['status' => 'A']);

Terakhir, jangan lupa untuk menyalin kedua method tersebut beserta isinya ke dalam class LoginController. Dan, seharusnya aplikasi yang kita bangun sudah berfungsi sesuai dengan spesifikasi contoh-contoh kasus di atas.

***

Tentunya, tidak dapat semua contoh kasus saya jabarkan di tulisan sini. Dalam dunia pemrograman sesungguhnya, ada ratusan atau bahkan ribuan kombinasi contoh kasus yang terjadi, tergantung dengan spesifikasi dari pemilik aplikasi.

Pengenalan custom login di tulisan ini memberikan gambaran bagi kalian yang ingin memanfaatkan fitur auth di Laravel, namun tanpa harus membuatnya dari awal.

Terakhir, sebagai informasi, tak hanya fitur login yang menggunakan trait seperti di atas. Fitur seperti register dan password juga mempunyai konsep yang sama. Yang perlu kalian perhatikan adalah nama trait yang digunakan, serta memahami sedikit demi sedikit fungsi dalam trait tersebut.

Read more »

Memisah File Log Aplikasi Laravel 5.1

Apa Itu Log Aplikasi?

Log aplikasi adalah segala catatan terkait dengan aplikasi kita. Catatan ini biasanya dituliskan oleh developer (atau otomatis ditulis oleh framework yang dipakai) untuk membantu proses debugging atau bug fixing di kemudian hari.

Laravel secara default menyimpan log aplikasi di file storage/logs/laravel.log. Setiap error atau exception yang terjadi saat aplikasi berjalan akan disimpan di file tersebut.

Jika kita ingin menambah log secara manual, kita bisa memanggil beberapa fungsi yang sudah disediakan:

Log::emergency($log);
Log::alert($log);
Log::critical($log);
Log::error($log);
Log::warning($log);
Log::notice($log);
Log::info($log);
Log::debug($log);

Urutan fungsi-fungsi di atas juga menyatakan level seberapa penting log tersebut, dimulai dari emergency yang paling penting dan diakhiri dengan debug yang tidak terlalu penting. Dokumentasi tentang Log bisa dibaca lebih lengkap di website Laravel.

Yang menjadi masalah adalah, apapun fungsi yang kita panggil, semua log akan ditulis ke dalam satu file yang sama, yaitu laravel.log. Jadi log untuk debugging aplikasi bercampur dengan log terkait error aplikasi. Hal ini sedikit menyusahkan ketika ternyata aplikasi kita masih banyak errornya, sehingga log debugging kita dengan cepat ‘tenggelam’ ditimpa log error yang mengalir tiada henti :D.

Tantangan

Bagaimana caranya memisah file log untuk masing-masing level? Jadi Log::error() akan ditulis ke error.log, Log::info() ditulis ke info.log, dan Log::debug() ditulis ke debug.log.

(Pencarian) Solusi

Pencarian solusi dari tantangan ini sedikit berliku. Sumber pertama tetap website laravel.com. Di bagian konfigurasi logging dijelaskan bahwa di belakang layar Laravel menggunakan library Monolog. Jika kita ingin memodifikasi perilaku Log bawaan Laravel, kita bisa membuka file app/bootstrap/app.php dan menambahkan kode berikut di akhir baris tepat sebelum return $app:

$app->configureMonologUsing(function($monolog) {
    $monolog->pushHandler(...);
});

Pertanyaan selanjutnya, apa yang harus ditambahkan di pushHandler? Apa itu pushHandler?

Pencarian berlanjut ke sebuah diskusi di laravel.io dengan penemuan potongan kode berikut:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$view_log = new Logger('View Logs');
$view_log->pushHandler(new StreamHandler('path/to/log.log', Logger::INFO));

$view_log->addInfo("User $user clicked");

Ada sedikit pencerahan, tapi solusi belum terbayang, maka pencarian terus dilanjutkan. Tujuan berikutnya adalah sebuah diskusi di laracasts.com. Disini ada potongan kode yang mirip dengan kode sebelumnya:

$bubble = false;

// Stream Handlers
$infoStreamHandler = new StreamHandler( storage_path("/logs/laravel_info.log"), Monolog::INFO, $bubble);
$warningStreamHandler = new StreamHandler( storage_path("/logs/laravel_warning.log"), Monolog::WARNING, $bubble);
$errorStreamHandler = new StreamHandler( storage_path("/logs/laravel_error.log"), Monolog::ERROR, $bubble);

// Get monolog instance and push handlers
$monolog = $log->getMonolog();
$monolog->pushHandler($infoStreamHandler);
$monolog->pushHandler($warningStreamHandler);
$monolog->pushHandler($errorStreamHandler);

Akhirnya pencarian dilanjutkan ke halaman github Monolog dan membaca source code.

Sampai disini mulai muncul beberapa temuan penting:

  • Laravel menggunakan Monolog
  • Monolog punya fungsi pushHandler
  • Ada 3 parameter penting di pushHandler:
    • Handler itu sendiri
    • Level log yang ingin di handle
    • $bubble, apakah log ini akan diteruskan ke atas (ke level yang lebih rendah).

Handler

Handler ini mengatur aksi apa yang akan dilakukan terkait log yang terjadi. Yang paling lumrah adalah menulikan ke file. Tapi bisa juga log ini dikirim via email, diteruskan ke syslog, atau dikirim ke layanan manajamen log seperti loggly. Daftar lengkap handler yang didukung oleh Monolog bisa dilihat disini.

Level Log

Seperti sudah disebutkan sebelumnya, ada delapan level log yang tersedia dan sudah baku digunakan. Parameter level log ini memungkinkan kita untuk mendaftarkan handler yang berbeda untuk setiap level. Misalnya untuk log error dikirim ke email, tapi kalau debug dan warning cukup ditulis ke file saja.

Bubble

Parameter $bubble mengindikasikan apakah setelah sebuah log diproses oleh handler tertentu akan diteruskan ke handler lainnya (jika memang ada).

Untuk lebih jelasnya, silakan praktekkan kode berikut ini:

...
$bubble = false; // silakan diganti true atau false, dan lihat hasilnya
$monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/error1.log", \Monolog\Logger::ERROR, $bubble));
$monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/error2.log", \Monolog\Logger::ERROR, $bubble));
...

Lalu panggil kode berikut dari manapun:

\Log::error('error');    

Jika $bubble=true maka error log akan tercatat di kedua file, sedangkan jika $bubble=false error log hanya akan tercatat di file error2.log (handler yang terakhir didaftarkan).

Solusi

Dari hasil pencarian di atas, akhirnya ketemu solusi seperti berikut ini:

$app->configureMonologUsing(function ($monolog) use ($app) {
    $bubble = false;

    $monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/debug.log", Logger::DEBUG,
        $bubble));
    $monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/info.log", Logger::INFO,
        $bubble));            
    $monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/notice.log", Logger::NOTICE,
        $bubble));

}); 

Atau dengan sedikit ilmu ‘opreker’, kita tahu bahwa Monolog sudah memiliki fungsi getLevels() sehingga kode diatas bisa dipercantik menjadi seperti ini:

$app->configureMonologUsing(function ($monolog) use ($app) {
    $bubble = false;

    foreach ($monolog->getLevels() as $name => $level) {
        $name = strtolower($name);
        $monolog->pushHandler(new \Monolog\Handler\StreamHandler($app->storagePath() . "/logs/{$name}.log", $level,
            $bubble));
    }
}); 

Kembali mengingatkan, kode diatas ditambahkan ke file app/bootstrap/app.php, di akhir baris tepat sebelum return $app.

Read more »

Memodifikasi Default Login Laravel 5.1

Artikel ini untuk Laravel 5.1 dan ada baiknya Anda membaca dulu artikel tentang Autentikasi Default Laravel 5.1.

Jika Anda merasa fitur autentikasi bawaan Laravel tidak mencukupi kebutuhan dan berniat membuat autentikasi sendiri, sebaiknya baca dulu artikel ini sampai tuntas. Siapa tahu kebutuhan Anda sebenarnya bisa diakomodir, hanya saja belum tahu caranya.

1. Login Dengan Username

Default login Laravel menggunakan email dan password untuk mengidentifikasi akun. Namun kita bisa dengan mudah mengganti email menjadi username. Caranya seperti di bawah ini:

// 1. tambahkan property $username ke AuthController
class AuthController extends Controller
{
    protected $username = 'username'; // 'username' bisa diganti sesuai kebutuhan
    ...

// 2. ganti field email menjadi username di auth/login.blade.php
// sebelum
<input type="email" name="email" value="">

// sesudah
<input type="username" name="username" value="">

Sekali lagi, jika Anda belum pernah menggunakan autentikasi bawaan Laravel, baca kembali tutorial Autentikasi Default Laravel 5.1.

2. Mengganti Redirect Setelah Registrasi

Defaultnya setelah berhasil registrasi akan diredirect ke /home. Untuk mengubah url redirect, tambahkan property $redirectPath ke AuthController dan isi sesuai kebutuhan:

class AuthController extends Controller
{
 $redirectPath = 'dashboard/profile';

3. Mengganti Redirect Setelah Login

Jika halaman yang dituju setelah login sama dengan halaman yang dituju setelah registrasi, maka kita tidak perlu melakukan apa-apa. Tapi jika berbeda, misalnya setelah login diredirect ke dashboard/welcome, maka kita harus tambahkan fungsi berikut ini ke AuthController:

public function authenticated($request, $user)
{
 // Fungsi ini akan dipanggil setelah user berhasil login.
 // Kita bisa menambahkan aksi-aksi lainnya, misalnya mencatat waktu last_login user.
 return redirect('dashboard/welcome');
}

4. Menambahkan Pengecekan Status User

Seringkali tabel user memiliki kolom status yang isinya active, blocked atau pending. Lalu hanya user yang statusnya active yang boleh login. Login default Laravel tidak melakukan pengecekan seperti ini. Untuk itu kita harus memodifikasi lagi AuthController dengan menambahkan fungsi seperti ini:

// Fungsi getCredentials ini aslinya ada di Illuminate\Foundation\Auth\AuthenticatesUsers.
// Yang dilakukan disini adalah meng-override fungsi tersebut dan menambahkan kolom status dalam pengecekan.
protected function getCredentials(Request $request)
{
 // aslinya
 // return $request->only($this->loginUsername(), 'password');
  
 // dimodifikasi jadi seperti ini
 return $request->only($this->loginUsername(), 'password') + ['status' => 'active'];
}

5. Otomatis Logout Jika Browser Ditutup

Buka file config/sessions.php, cari baris berikut dan ubah nilainya menjadi true:

'expire_on_close' => false,

Penutup

Sekian 5 modifikasi autentikasi bawaan Laravel versi On The Spot. Trik-trik seperti ini tidak ditemui dalam dokumentasi resmi di website laravel.com. Hanya Tuhan, Taylor Otwell, dan Anda yang suka menelusuri source code yang tahu. Keep reading !

Read more »

Cara Intall Laravel 5.6 2018

Saya rekomendasikan Anda untuk menginstall composer terlebih dahulu. Atau Anda bisa membaca kembali postingan terdahulu tentang cara install composer di website ini.

Cara 1: Via Installer Laravel

Pertama, download installer laravel:

composer global require "laravel/installer"

Selanjutnya, jalankan perintah berikut:

laravel new blog

Kelebihan

  • Relatif lebih cepat.
  • Keywordnya lebih simpel dan mudah diingat.
  • Dijamin mendapatkan update kode terbaru.

Kekurangan

  • Perlu koneksi internet untuk mendowloand library lainnya.
  • Perlu satu langkah tambahan untuk mendownload installer laravel.

Perkiraan Waktu

  • 2 menit*

Cara 2: Via composer create-project

Setelah Anda berhasil menginstall composer, cukup jalankan perintah berikut ini di terminal/console/command prompt Anda:

composer create-project --prefer-dist laravel/laravel blog

Kelebihan

  • Singkat, cukup satu langkah.

Kekurangan

  • Perlu koneksi internet untuk mendowloand library lainnya.
  • Relatif membutuhkan waktu yang lama.

Perkiraan Waktu

  • 10 menit*

Cara 3: Download Source Laravel Secara Lengkap

Klik disini untuk mendownload source Laravel siap pakai (sudah lengkap dengan library lain yang dibutuhkan). Ekstrak file tersebut di document root server Anda (htdocs, www, atau yang sejenisnya). Laravel siap dijalankan.

Kelebihan

  • Ini cara yang paling dikenal oleh rata-rata programmer: download source code, taruh di htdocs, aplikasi bisa langsung diakses.
  • Relatif paling cepat.
  • Tidak perlu koneksi internet untuk mendownload library lain yang dibutuhkan.

Kekurangan

  • Bisa jadi kode yang Anda download bukan kode terbaru. Oleh karena itu cara ini sebenarnya tidak dianjurkan, kecuali Anda cuma ingin mencicipi Laravel secara cepat dan tidak mau dipusingkan dengan composer.

Perkiraan Waktu

  • 1 menit*

Untuk cara ketiga, sebenarnya update library tetap bisa dilakukan kapanpun Anda mau. Begitu terhubung dengan internet, cukup jalankan perintah composer update maka otomatis library akan diperbarui. Yang membedakan hanyalah cara Anda mendapatkan library-library tersebut untuk pertama kali.

*Perkiraan waktu didapatkan dengan ujicoba pada jaringan internet dengan kecepatan download 200 KB/s.

Read more »

Configuration Laravel 5.6 2018

Configuration

Introduction

All of the configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.

Environment Configuration

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 the .env file when running PHPUnit tests or executing Artisan commands with the --env=testing option.

{tip} Any variable in your .env file can be overridden by external environment variables such as server-level or system-level environment variables.

Environment Variable Types

All variables in your .env files are parsed as strings, so some reserved values have been created to allow you to return a wider range of types from the env() function:

.env Value env() Value
true (bool) true
(true) (bool) true
false (bool) false
(false) (bool) false
empty (string) ''
(empty) (string) ''
null (null) null
(null) (null) null

If you need to define an environment variable with a value that contains spaces, you may do so by enclosing the value in double quotes.

APP_NAME="My Application"

Retrieving Environment Configuration

All of the variables listed in this file will be loaded into the $_ENV PHP super-global when your application receives a request. However, you may use the env helper to retrieve values from these variables in your configuration files. In fact, if you review the Laravel configuration files, you will notice several of the options already using this helper:

'debug' => env('APP_DEBUG', false),

The second value passed to the env function is the "default value". This value will be used if no environment variable exists for the given key.

Determining The Current Environment

The current application environment is determined via the APP_ENV variable from your .env file. You may access this value via the environment method on the App facade:

$environment = App::environment();

You may also pass arguments to the environment method to check if the environment matches a given value. The method will return true if the environment matches any of the given values:

if (App::environment('local')) {
    // The environment is local
}

if (App::environment(['local', 'staging'])) {
    // The environment is either local OR staging...
}

{tip} The current application environment detection can be overridden by a server-level APP_ENV environment variable. This can be useful when you need to share the same application for different environment configurations, so you can set up a given host to match a given environment in your server's configurations.

Accessing Configuration Values

You may easily access your configuration values using the global config helper function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exist:

$value = config('app.timezone');

To set configuration values at runtime, pass an array to the config helper:

config(['app.timezone' => 'America/Chicago']);

Configuration Caching

To give your application a speed boost, you should cache all of your configuration files into a single file using the config:cache Artisan command. This will combine all of the configuration options for your application into a single file which will be loaded quickly by the framework.

You should typically run the php artisan config:cache command as part of your production deployment routine. The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development.

{note} If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null.

Maintenance Mode

When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, a MaintenanceModeException will be thrown with a status code of 503.

To enable maintenance mode, execute the down Artisan command:

php artisan down

You may also provide message and retry options to the down command. The message value may be used to display or log a custom message, while the retry value will be set as the Retry-After HTTP header's value:

php artisan down --message="Upgrading Database" --retry=60

Even while in maintenance mode, specific IP addresses or networks may be allowed to access the application using the command's allow option:

php artisan down --allow=127.0.0.1 --allow=192.168.0.0/16

To disable maintenance mode, use the up command:

php artisan up

{tip} You may customize the default maintenance mode template by defining your own template at resources/views/errors/503.blade.php.

Maintenance Mode & Queues

While your application is in maintenance mode, no queued jobs will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode.

Alternatives To Maintenance Mode

Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like Envoyer to accomplish zero-downtime deployment with Laravel.

Read more »

Isntall Laravel 5.6 2018


Installation

Installation

{video} Are you a visual learner? Laracasts provides a free, thorough introduction to Laravel for newcomers to the framework. It's a great place to start your journey.

Server Requirements

The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the Laravel Homestead virtual machine, so it's highly recommended that you use Homestead as your local Laravel development environment.

However, if you are not using Homestead, you will need to make sure your server meets the following requirements:

  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension

Installing Laravel

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

Via Laravel Installer

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Make sure to place composer's system-wide vendor bin directory in your $PATH so the laravel executable can be located by your system. This directory exists in different locations based on your operating system; however, some common locations include:

  • macOS: $HOME/.composer/vendor/bin
  • GNU / Linux Distributions: $HOME/.config/composer/vendor/bin

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel's dependencies already installed:

laravel new blog

Via Composer Create-Project

Alternatively, you may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project --prefer-dist laravel/laravel blog

Local Development Server

If you have PHP installed locally and you would like to use PHP's built-in development server to serve your application, you may use the serve Artisan command. This command will start a development server at http://localhost:8000:

php artisan serve

Of course, more robust local development options are available via Homestead and Valet.

Configuration

Public Directory

After installing Laravel, you should configure your web server's document / web root to be the public directory. The index.php in this directory serves as the front controller for all HTTP requests entering your application.

Configuration Files

All of the configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.

Directory Permissions

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

Application Key

The next thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer or the Laravel installer, this key has already been set for you by the php artisan key:generate command.

Typically, this string should be 32 characters long. The key can be set in the .env environment file. If you have not renamed the .env.example file to .env, you should do that now. If the application key is not set, your user sessions and other encrypted data will not be secure!

Additional Configuration

Laravel needs almost no other configuration out of the box. You are free to get started developing! However, you may wish to review the config/app.php file and its documentation. It contains several options such as timezone and locale that you may wish to change according to your application.

You may also want to configure a few additional components of Laravel, such as:

Web Server Configuration

Pretty URLs

Apache

Laravel includes a public/.htaccess file that is used to provide URLs without the index.php front controller in the path. Before serving Laravel with Apache, be sure to enable the mod_rewrite module so the .htaccess file will be honored by the server.

If the .htaccess file that ships with Laravel does not work with your Apache installation, try this alternative:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Nginx

If you are using Nginx, the following directive in your site configuration will direct all requests to the index.php front controller:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Of course, when using Homestead or Valet, pretty URLs will be automatically configured.


Read more »


© adimancv.com