Memaparkan catatan dengan label bahasa melayu. Papar semua catatan
Memaparkan catatan dengan label bahasa melayu. Papar semua catatan

Laravel part 6 - Migration

Mencipta table student menggunakan migration. Migration ialah pembinaan database yang boleh di rollback dan ala-ala github gitu tetapi dalam bentuk database.

php artisan make:migration create_students_table
Created Migration: 2019_10_17_141304_create_students_table


Boleh rujuk di:
https://laravel.com/docs/5.8/migrations

Secara default didalam file create_students_table akan mengandungi id dan timestamps:

    public function up()
    {
        Schema::create('students'function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });
    }


Kita akan buat penambahan didalam  table ini. Untuk dokumentasi cara bina dan jenis-jenis type data boleh lihat di: https://laravel.com/docs/5.8/migrations#creating-columns

Kita ingin menambah column nama, no ic, email dan major ke celah-celah diantgara id dan timestamps.

    public function up()
    {
        Schema::create('students'function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nama');
            $table->char('noic',15)->unique();
            $table->string('email')->unique();
            $table->string('major');
            $table->timestamps();
        });
    }

kemudian, pergi ke terminal untuk migrate script ini dan run:
php artisan migrate

jika kita tengok, selain script create_students_table, terdapat dua lagi script yang dirun, itu adalah file default yang kita boleh delete dari folder database di dalam laravel.
manakala terdapat table pelajar, yang kita gunakan semasa laravel part 5. Ianya adalah yang asal dicipta menggunakan mysql dan bukan migrate.

Untuk undo semua script migration:
php aritsan migrate:rollback


Namun bagi file pelajar yang kita bina menggunakan mysql, ianya tidak rollback kerana script tersebut tiada didalam folder database dalam laravel

Jom kita melihat struktur data di dalam pelajar



Sekarang tambah 4 data untuk kita test. Table students tersebut sebenarnya sama sahaja data & datatype yang telah kita bina di tutorial ke 6 tempoh hari. Jadi kita boleh menukar table dari pelajardb kepada students di PelajarController untuk melihat hasilnya

class PelajarController extends Controller
{
    public function index()
    {
      $pelajar = DB::table('students')->get();
  
       return view('pelajar.index',['pelajar'=>$pelajar]);
    }
}

hasilnya:

Alhamdulillah. Siap bina database menggunakan migration. Sekarang kita akan membina model pula. Sila ke pelajaran seterusnya.

Install Extension Untuk Visual Code Studio - Laravel

1- Advanced New File by Dominik Kundel
2- Auto Close Tag  by Jun Han
3- Bootstrap 3 Snippets by William Whitehead
4- Bootstrap v4 Snippets by Zaczero
5- Bootstrap 4, font awesome 4, font awesome 5 free by Ashok Koyi
6- DotENV by mikestead
7- Laravel Blade Snippets by Winnie Lin
8- Laravel Artisan by Ryan Naddy
9- Laravel 5 snippets by Winnie Lin
10 - Laravel 5 snippets  by Sachit Tandukar
11- Night Owl (Vs Code Theme) by Sarah Drasner
12- PHP Formatter by Sophisticode
13- PHP IntelliSense by Felix Becker
14-  PHP Namespace Resolver by Mehedi Hassan



Laravel Part 5 - Menyambung Connection Database & View field




1. Cipta database bernama pelajardb yang mengandungi :


2.  Isi data dua atau lebih.


3. Edit file .env dan sesuaikan dengan server mysql kita. DB_DATABASE kita letak nama pelajardb yang telah kita cipta.


Create controller bernama PelajarController menggunakan terminal dgn command

php artisan make:controller PelajarController -resource


Buka file controller Pelajar Controller.php

letak
use Illuminate\Support\Facades\DB;



namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;


class PelajarController extends Controller
{
    public function index()
    {
      $pelajar = DB::table('pelajar')->get();
  
       return view('pelajar.index',['pelajar'=>$pelajar]);
    } }
command  $pelajar = DB::table('pelajar')->get(); bertujuan menyenaraikan semua di dalam table pelajar dan meng-assign-kan nilai tersebut ke $pelajar  .

Semua maklumat tadi berada dalam bentuk array, kerana ada dua row data yang telah kita masukkan, oleh itu kita hantar nilai $pelajar  ke paparan view iaitu ke blade index.blade.php yang terletak di dalam folder pelajar di dalam view.




4.  Di dalam blade di view (index.blade.php) , kita akan membuat @foreach iaitu    @foreach ($pelajar as $pel) untuk memanggil nilai  $pelajar  yang telah dihantar oleh controller untuk kita asingkan mengikut baris.

command:
{{ $loop->iteration }}
kita gunakan untuk paparkan bilangan kiraan rekod yang telah kita jalankan.


@extends('layout.main')

@section ('title','Portal Encraption.blogspot.com')

@section('container')
<div class="container">
  <div class="row">
    <div class="col-10">
      <h1 class="mt-3">Daftar Pelajar</h1>


      <table class="table">
        <thead class="thead-dark">
          <tr>
            <th scope="col">#</th>
            <th scope="col">Nama</th>
            <th scope="col">Email</th>
            <th scope="col">Major</th>
            <th scope="col">Tindakan</th>
          </tr>
        </thead>
      
        <tbody>
          @foreach ($pelajar as $pel)
            <tr>
                <td>{{ $loop->iteration }}</td>
               <td>{{ $pel->nama }}</td>
                <td></th>{{ $pel->email }}</td>
                <td>{{ $pel->major }}</th>
                <td>
                    <a href="" class="badge badge-success">edit</a>
                    <a href="" class="badge badge-danger">delete</a></td>
              </tr>
              @endforeach

        </tbody>


      </table>
    </div>
  </div>
</div>
@endsection


?>

output:




Download di sini

Laravel Part 4 - Mengirim Nilai Di Route kepada View

Ekperimen kali ini cuba mengirim nilai dari web.php (route) kepada view pelajar.

Di fail route, kita assign nilai pada nama tersebut.

<?php

Route::get('/pelajar', function () {
    $nama = 'Mr Encraptor Samado';
    return view('pelajar',['nama' => $nama]);
});
?>

Kemudian di page view pelajar,  hanya menggunakan memanggil menggunakan {{nama}} sahaja seperti
<?php
@section('container')
<div class="container">
  <div class="row">
    <div class="col-10">
      <h1 class="mt-3">Ini Section Pelajar!</h1>
      <br>
      Selamat datang, {{$nama}}!
    </div>
  </div>
</div>
@endsection
?>

Output:

 

Mudah bukan?

Laravel Part 3 - Memusatkan Layout Untuk Memudahkan Pengeditan (master layout)

Seperti anda ketahui, website biasanya mempunyai paparan sama sahaja, hanya content sahaja yang berubah.

Untuk itu, kita boleh memindahkan semua element kecuali content kita ke satu page yang khas, di mana kita akan panggil page tersebut yang mungkin mengandungi header dan footer dan navbar, namun isinya pula, kita akan buat page-page baru. Maknanya content sahaja berada di page-page baru, layoutnya kita tempatkan pada satu page yang satu sahaja.

Jom kita bina master layout


Create folder dibawah folder views, namakan layout. create file bernama main.blade.php, copy semua di dalam welcome.blade.php ke adalam layout/main.blade.php. Kita namakan main.blade.php ini sebagai page induk.

Setiap page akan berubah title  walaupun struktur displaynya adalah sama. Oleh itu kita akan menggunakan @yield('title') di page induk ini (main.blade.php), dan nilai 'title' itu akan dihantar oleh page-page yang lain menggunakan command @section, sebagai contoh nilai title itu kita namakan Portal rasmi James Bond, oleh itu di child page, kita akan taip aturcara seperti @section('title','Portal Rasmi James Bond') untuk menghantar value tersebut ke tempat @yield('title') tadi.








Download Files Yang Berkaitan Dengan Tutorial Laravel Part 3

Laravel Part 2 - Berkenalan dengan folder asas


Didalam Laravel, terdapat folder Views dan Routes yang memainkan peranan penting. Jika kita mula-mula instal Laravel, terdapat hanya satu sahaja file di dalam folder Views iaitu welcome.blade.php. Segala berkaitan coding yang melibatkan display antara muka diletakkan di sini.

Di folder ini, semakan banyak page yang akan dipaparkan, semakin banyak file ber-extension .blade.php akan dibuat di folder Views.


Manakala di folder routes pula, terdapat satu file bernama web.php. Disini semua aturan berkaitan route akan digunakan sepenuhnya.
 Sebagai contoh, / ialah home, kita akan hantar kepada file view yang bernama index.blade.php, begitu /about, kita akan kepada view about.blade.php

Manakala  jika kita lihat isi kandungan fail-fail ber-extension blade.php, ianya seperti dibawah:


ianya bertujuan untuk page paparan.




Laravel Part 1 - Memulakan Projek Laravel - Instalasi Laravel


Perlu ada 3 perkara yang telah siap di install ke dalam komputer sebelum memulakan pembangunan sistem menggunakan kerangka Laravel

3 perkara tersebut ialah:

1. Xampp  (https://www.apachefriends.org/download.html)
2. Composer  (https://getcomposer.org/)
3. Git Batch  ( https://git-scm.com/download/win)



composer create-project --prefer-dist laravel/laravel cubaLaravel
.


Setelah siap laravel di download, boleh masuk ke folder sistem tersebut dan run

cd cubaLaravel/
php artisan serve






Localhost sistem laravel dalam folder public, dibuka pada port 127.0.0.1:8000

Boleh test di browser:


Bersambung. 




6- Laravel - Routing Controllers - Resource

test


5- Laravel - Routing Controllers - Penghantaran Nilai


1) Bermula penghantaran nilai atau passing value.  Mulakan dengan nilai value id.

Fail Routes:

1

2) Fail Controller bernama PostController menerima route get Posts dan memproses value {id} yang dihantar pada function index

2

3) Paparan

3


4- Laravel - Routing Controllers

1) Mewujudkan fail Controller yang baru bernama PostsController

$ php artisan make:controller --resource PostsController1

2) Di bahagian function index pada fail Controller bernama PostsController tadi,  letakkan satu penyataan menyatakan index telah berjaya dijalankan.

public function index()
{
     //
     return "Index telah dijalankan. Tahniah";
}

2

3)  Panggil controller tadi dengan laluan panggilan url get bernama posts (http://localhost:3000/cms/public/posts) ,  dan bila buka di browser pada panggilan get posts ini, maka route menyatakan bahawa controller akan mengawal laluan ini dan fail controller itu yang dimaksudkan iaitu PostsController. Dan didalam fail controller tadi, terletak banyak function. Namun apa yang diminta oleh panggilan url bernama posts ini ialah function index().

Route::get('/posts','PostsController@index');

3

Penyataan:

1- Posts ialah laluan iaitu http://localhost:3000/cms/public/posts
2-  Nama controller yang mengawal get posts ini ialah PostsController
3-  Nama function yang akan handle get posts ini yang terletak dalam controller PostsController ialah index.

4


2- Laravel - Routes

Fail Routes berada di folder app->Http

routes

Hasil:

routes2


Code:

route9a


Hasil:

route9

Untuk semak route, guna command di git bash:

php artisan route:list

routes10

Namun, kalau tengok di kotak Name, tiada nama. bagaimana mengisi nama tersebut? Guna array untuk namakan field tersebut:


2018-03-14_110504

Pergi ke browser, dan taip:
http://localhost:3000/cms/public/admin/posts/example
outputnya adalah:

2018-03-14_110803

Route nya juga telah dinamakan. Lihat:


2018-03-14_110918


Laravel : if endif for endfor

          @for ($i=0; $i<5; $i++)
                 @if ($i % 2 === 0)
                      
  • Iteration {{ $i+1 }}
  • @endif @endfor






    Asas @yield dan @section didalam Laravel (Bahasa Melayu/Malaysia)

    1. Kita buat panggilan 3 @yield in Main Layout
    -- HTML headers ... 
    
    @yield('css')
    
    -- HTML Body 
    
    @yield('content')
    
    -- HTML footer
    
    @yield('javascript')
    


    2. Kemudian kita pecahkan isi javascript,content dan css mengikut section untuk dipanggil. Setiap @section perlu berakhir dengan @stop.
    // for example in main.blade.php
    @section('css')
        
    @stop
    @section('content')
        // content of main
    @stop
    @section('javascript')
        

    Aturcara Ringkas Penggunaan Laravel (Bahasa Melayu)

    1. http->routes.php
    Route::get('/', function () {
        return view('home');
    });
    
    

    2.public->resources->views->home.blade.php
    @extends('layouts.master')
    @section('content')
    

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

    @endsection

    3. public->resources->views->layouts->master.blade.php
    
    
        
            
            @yield('title')
     	
            
            @yield('styles')
            
            
            @include('includes.header')
            
    @yield('content')

    4. public->resources->views->includes->header.blade.php

    5. public->src->css->main.css
    body {
        font-family: "Roboto", sans-serif;
        font-size: 16px;
    }
    
    h1 {
        font-size: 48px;
        margin: 8px 0;
    }
    
    .main {
        padding: 0 32px;
    }
    
    .centered {
        text-align: center;
        vertical-align: middle;
    }
    
    header {
        position: relative;
        padding: 16px 32px
    }
    
    footer {
        position: absolute;
        padding: 16px 0;
        bottom: 0;
        left: 50%;
        -webkit-transform: translate(-50%, 0);
        -moz-transform: translate(-50%, 0);
        -ms-transform: translate(-50%, 0);
        -o-transform: translate(-50%, 0);
        transform: translate(-50%, 0);
    }
    
    nav ul {
        padding: 0;
        margin: 0;
        list-style: none;
        text-align: center;
    }
    
    nav li {
        display: inline-block;
        padding: 0 16px;
    }
    
    header nav li:first-of-type {
        padding-left: 0;
    }
    
    header nav li:last-of-type {
        padding-right: 0;
    }
    
    nav a {
        color: darkgrey;
        text-decoration: none;
    }
    
    header nav a {
        font-size: 26px;
        font-weight: bold;
    }
    
    footer nav a {
        font-size: 12px;
    }
    
    header nav a:hover {
        color: salmon;
    }
    
    

    Javascript : Object 1

    Objek membenarkan kita menyimpan properties dan beberapa nilai bagi object itu sendiri. Bagaimana kita nak membuat simple Object? Declare object perlu ada: 1) var 2) diikuti dengan nama objek 3) diikuti dengan tanda sama = 4) Setiap objek kemudian mempunyai tanda { 5) ada info didalam breket { tadi 6) berakhir dengan } Ini adalah contoh dimana info tiada didalam breket.

    var bob = {};


    Ini pula contoh objek terdiri daripada info yang dikenali sebagai property. Kaedah memasukkan property adalah nama property, diikuti tanda noktah bertindih( : ) dan nilai bagi property tersebut. Jika kita mempunyai banyak property, ianya perlu dipisahkan dengan tanda koma ( , ). Contoh seperti dibawah:



    var Spencer = {
    age: 22,
    country: "United States"
    };

    // make your own object here called me
    var me = {
    age:27,
    country:"Pulai Chondong"
    };


    Akses Properties Dalam Object Cara Pertama

    Guna Object Literal Notation - Dot Notation

    Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam braket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation {} .

    1) Dot Notation

    Cara mudah adalah Var = .



    var bob = {
    name: "Bob Smith",
    age: 30
    };
    var susan = {
    name: "Susan Jordan",
    age: 25
    };
    // here we save Bob's information
    var name1 = bob.name;
    var age1 = bob.age;
    // finish this code by saving Susan's information
    var name2 =susan.name;
    var age2 = susan.age;


    Akses Properties Dalam Object Cara Kedua

    Guna Object literal notation - Bracket Notation


    Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam curly bracket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation [] .

    1) Bracket Notation

    // Take a look at our next example object, a dog
    var dog = {
    species: "greyhound",
    weight: 60,
    age: 4
    };

    var species = dog["species"];
    // fill in the code to save the weight and age using bracket notation
    var weight = dog["weight"];
    var age =dog["age"];


    Akses Properties Dalam Object Cara Ketiga
    Constructor

    Apa itu constructor? Constructor adalah cara mencipta objek tanpa curly bracket {}. Cipta objek menggunakan constructor iaitu mencipta objek kosong terlebih dahulu () dan syntaxnya adalah :


    var objectName = new Object();


    Kita sudah istihar objek tanpa properties.



    var bob = new Object();



    Bagaimana pula ingin masukkan properties? dengan cara kita create nama property tersebut contoh nama @ umur selepas . dan kemudian assign kepada nilai yang dikehendaki. Lihat contoh:


    var bob = new Object();
    bob.nama = "Bob Amirul";
    bob.umur = 30;

    Javascript: For (var property in dog)


    var dog = {
    species: "bulldog",
    age: 3,
    color: brown
    };

    for(var property in dog) {
    console.log(property);
    }


    The words var and in are keywords. We need them to always be there. We can replace dog with any object that we want the for-in loop to run through. And you can think of property as a placeholder variable. You can use any word you want here.

    In English, what is the code doing? It says: Assign the first property of the dog object to the variable property. Run the code (here, it is to print property to console). Then assign the second property of the dog object to the variable property. Again, run the code in the curly brackets. Keep repeating this until all the properties of the dog have been assigned to property.

    Javascript: Object

     

    - - - B a s i c s - - -

    Each Object has one or more properties.
    Each property consists of a property-key and it's associated value.

     var object1 = {
    name: "First"
    }


    So object1 has 1 property
    a name property with property-key name and it's associated string VALUE "FIRST"

    OR

    var myObj = {
    type: 'fancy',
    disposition: 'sunny'
    }


    myObj has 2 properties seperated by a comma-,,
    a type property with property-key type and an associated string VALUE 'fancy'
    a disposition-property with property-key disposition and
    ..an associated string VALUE 'sunny'.

    = = = = = = = = = = = = = = = = = = = = = = =
    To create an Object,
    you can use the literal notation,
    you directly create an Instance of the object, with the
    properties being separated by a comma-,


    var myObj = {
    type: 'fancy',
    disposition: 'sunny'
    };


    OR
    You create an Object by the construct notation.
    First you create an empty Object by way of either
    myObj = new Object(); or myObj = {};
    and then you attach its properties using the syntax
    object-name.property-key = it's-associated-value ;
    ( this.name = x ; )

    thus:

    var myObj = {};
    myObj.type = 'fancy';
    myObj.disposition = 'sunny';



    OR

    There is also the facility Class construct notation.
    The name should then start with a Capital-letter



    var Person = function( theName, theAge ) {
    this.name = theName;
    this.age = theAge;
    this.displayInstance = function() {
    console.log("The displayInstance -output-"+
    "\n============================" +
    "\n\t name: " + this.name +
    "\n\t age: " + this.age);
    };
    };
    //now create an Instance of this Class-object
    var myObj = new Person("Classy_Rocker",20);
    //call the Method displayInstance which takes NO parameters
    myObj.displayInstance();
    console.log( myObj );


    As you can see i created a function within this constructor,
    they now call this function a Method.
    So if in near future the course is asking you to create a method you now know
    that you have to create
    a property-key with an associated value being a function within an Object.

    Javascript: Loop Mastery Practice

     

    LatihanKetiga2Loop

    LATIHAN

    Laksanakan ketiga-tiga For, Do/While dan While dalam satu aturcara.

    // Write your code below!

    var testFor= function(){
    for (i=1;i<10;i++){
    console.log ("ini adalah loop bagi for" +i);
    };
    };


    var testDoWhile= function(){
    hidupkanLoopDo=true;
    do {
    console.log ("Ini adalah loop bagi do untuk kali ini sahaja");
    }while (hidupkanLoopDo=false);

    };

    var testWhile=function(){
    i=1;
    while(i<10){
    console.log ("Ini adalah loop bagi While yang ke"+i);
    ++i;
    }
    }

    testFor();
    testDoWhile();
    testWhile();







    ini adalah loop bagi for1
    ini adalah loop bagi for2
    ini adalah loop bagi for3
    ini adalah loop bagi for4
    ini adalah loop bagi for5
    ini adalah loop bagi for6
    ini adalah loop bagi for7
    ini adalah loop bagi for8
    ini adalah loop bagi for9
    Ini adalah loop bagi do untuk kali ini sahaja
    Ini adalah loop bagi While yang ke1
    Ini adalah loop bagi While yang ke2
    Ini adalah loop bagi While yang ke3
    Ini adalah loop bagi While yang ke4
    Ini adalah loop bagi While yang ke5
    Ini adalah loop bagi While yang ke6
    Ini adalah loop bagi While yang ke7
    Ini adalah loop bagi While yang ke8
    Ini adalah loop bagi While yang ke9