Memaparkan catatan dengan label Programming. Papar semua catatan
Memaparkan catatan dengan label Programming. 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.

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


3- Laravel - Controllers Create

1. Controller boleh dibina dengan create file didalam sublime text. Tapi boleh juga dibuat di terminal dengan menaip:

php artisan make:controller PostController

4

Maka file controller juga diwujudkan seperti dibawah:

5

Namun kalau kita inginkan controller tersebut dipenuhi dgn resource seperti CRUD, boleh tambah command –-resource seperti:

$ php artisan make:controller --resource ArticlesController

6

Maka file controller diwujudkan dengan dilengkapi CRUD iaitu index, create, store, show, edit, update, destroy seperti dibawah:

7

8

9


3- Laravel - Introduction Controllers


1. Controller merupakan orang tengah.
2. Terletak di dalam folder app->Http->Controllers.
3. Main controller adalah bernama Controllers.php.
4. Didalam Controllers mengandungi:
    - namespace
   - use

Namespace adalah folder dimana controller file berada.  Dan use adalam dimana controller dipanggilcontroller3


Lihat keterangan dibawah


controller4


1. namespace digunakan untuk bagitau dimana file controller (yg dipanggil oleh no 2) itu berada.
2.  Folder nama Book. Juga merupakan folder fizikal. Dipanggil namespace.
3. Nama fail NotebooksController.php merupakan controller.
4. Sesuai digunakan Usecase ini jika ada fail yang sama nama seperti NotebooksController.php  juga berada di folder selain Book, contoh di folder Journal.

Dalam view juga perlu diubah Route::Resource untuk memanggil controller mana.

controller2


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






    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


    Javascript : Do / While

     

    Kadang-kadang, kita ingin loop kita berjalan at least satu kali. Oleh itu kita akan menggunakan Do/While untuk jalan mudah.

    var loopCondition = false;

    do {
    console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
    } while (loopCondition);


    It runs once because do tells it to, but then never again because loopCondition is false!



    LATIHAN



    1) Guna Do/While.

    2) Minta input dari user


    3) Display di console.log


    4) Matikan dengan falsekan kenyataan.



    var getToDaChoppa = function(){
    // Write your do/while loop here!
    do {
    var x = prompt ("Apa pilihan anda?");
    console.log (x);
    } while (jalankan=false);

    };

    getToDaChoppa();

    Javascript : While Part 1

     

    Jika for digunakan ketika kita tahu bila ia berhenti, While pula digunakan ketika kita tidak tahu bilakah dia akan berhenti.

     

    understand = true;

    while(understand === true){
    console.log("I'm learning while loops!");
    //Change the value of 'understand' here!
    understand=false;

    }


    Namun pastikan didalam while tersebut, ada jalan untuk dia berhenti dan keluar dari while tersebut dan tidaklah ianya berpusing sahaja forever dan akhirnya membawa kepada crash sesuatu sistem akibat while yang tidak keluar2 atau infinity.


    contoh diatas adalah understand=false;  adalah satu cara untuk kita hentikan penyataan while.


    Brevity is the soul of programming


    Ketahuilah brevity adalah key penting dlm programming, oleh itu, code diatas kita boleh ringkaskan menjadi:

    understand = true;

    while(understand){
    console.log("I'm learning while loops!");
    //Change the value of 'understand' here!
    understand=false;

    }

    understand itu kita tidak perlu tanya ===true didalam while.


    Penyataan diringkaskan seperti dibawah:

    var bool = true;
    while(bool){
    //Do something
    }


    daripada:

    var bool = true;
    while(bool === true){
    //Do something
    }

     


    Kedua-dua adalah sama sahaja, melainkan brevity dan kecepatan meringkas sahaja. Elakkan written the less succinct version dalam programming kita, sebaliknya teruskan  Correct it to the more elegant version!

    var bool = true;

    while(bool){
    console.log("Less in coding is too cool!");
    bool = false;
    }
    LATIHAN
    Bina satu coding menggunakan while, dengan penyataaan I'm looping! sebanyak tiga kali menggunakan while.
    Bagaimana menggunakan counter untuk while? Set variable kepada 0 di luar While, dan set counter tersebut bertambah semasa looping, dan set penyataan berhenti di While dengan nyatakan bilangan ke berapa ianya patut berhenti atau berapa kali ianya TRUE.
    //Remember to set your condition outside the loop!


    var loop = function(){
    while(count <3){
    //Your code goes here!
    console.log("I'm looping!");
    count++;
    }
    };

    var count=0;
    loop();





    I'm looping!
    I'm looping!
    I'm looping!

     


    CONTOH

    //Remember to make your condition true outside the loop!

    var soloLoop = function(){
    //Your code goes here!

    loopSekali=true;

    while (loopSekali){
    console.log("Looped once!");
    loopSekali = false;
    }

    };

    soloLoop();





    Looped once!

    Javascript : Loop Part 2- Array

     

    Variable boleh simpan number dan string, namun kita hanya boleh store 1 number atau satu string sahaja.
    Mujurlah kita punyai array. Apa guna array?

    a. store lists of data
    b. can store different data types at the same time
    c. are ordered so the position of each piece of data is fixed

    var arrayName = [data, data, data];

    var names = ["Mao","Gandhi","Mandela"];

    var sizes = [4, 6, 3, 2, 1, 9];

    var mixed = [34, "candy", "blue", 11];


     



    Bila mana anda lihat  data dilingkungi dgn tanda [ ], it is an array.



    Contoh:



    var profile = ["Nik","IT Manager",32,4];
    console.log(profile);






    ["Nik","IT Manager",32,4];



    1. First element in the array: profile[0]


    2. Third element in the array: profile[2]



    atau jika ingin mendapatkan data 32, maka gunakan profile[2]



    console.log(profile[2]);



    Kalau ada 4 elemen dalam array, ok la. Bagaimana dengan 100 elemen dalam Array? Kita akan gunakan Array.



    // Let's print out every element of an array using a for loop

    var cities = [ "Pulai Chondong", "Melbourne", "Amman", "Helsinki", "NYC", "Kota Bharu"];

    for (var i = 0; i < cities.length; i++) {
    console.log("I would like to visit " + cities[i]);
    }








    I would like to visit Melbourne
    I would like to visit Amman
    I would like to visit Helsinki
    I would like to visit NYC



    Keyword, ianya berhenti sebelum cities.length

    Javascript: Loop part 1

     

    Gunakan loop untuk mempermudahkan urusan kita.

    // Write five console.log statements.

    console.log(1);
    console.log(2;
    console.log(3);
    console.log(4);
    console.log(5);

    Kepada:


    for (var counter = 1; counter < 6; counter++) {
    console.log(counter);
    }

    atau


    for (var i = 1; i < 6; i = i + 1){
    console.log(i);
    }


     



    contoh bermula dari 4 hingga ke 23:



    for (var i = 4; i < 24; i = i + 1) {
    console.log(i);
    }


     



    We can increment up by any value by writing i += x, where x is how much we want to increment up by.e.g., i += 3 counts up by 3s.





    We can decrement down by any value by writing i -= x.



    Contoh:




    -Make it start counting from 5. Please!


    -Stop the counting when it prints out 50.


    -Only count every fifth number. So we want to increment i by 5.



    for (var i = 5; i < 51; i+=5) {
    console.log(i);
    }


    Contoh loop menurun adalah: 10 hingga ke 0.


    for (var i = 10; i >= 0; i--) {
    console.log(i);
    }


     


    Once more, for practice: write a forloop that gets the computer to count down from 100 until 0 by 5. This time, make sure not to print 0.

    // Write your very own for loop!

    for (var i=100;i>0;i-=5)
    {
    console.log(i);
    }