Laraveler


Showing posts with label Laravel 5.6. Show all posts
Showing posts with label Laravel 5.6. Show all posts

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 »

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