Monday, November 7, 2016

Howto Start Lavarel and MySQL


Lavarel provide the tools to quickly create an MVC application. In this guide, lets generate the required database table of a class and retrieve data while keeping to MVC.

Background

Models are used to represent objects and Laravel associates it with a database table of the same name. E.g. a model called Customer (singular) will have a table called Customers (plural). Using the --migration option will also produce a file to manage the database.
Our Customer class will consist of the fields id, cname, phone, last_update and a timestamp.



Controllers provide the glue to Views and Models. Laravel helps to create controllers that are empty or CRUD ready in the directory app/Http/Controllers. CRUD ready meaning that the standard functions or also known as Actions are generated for each HTTP action;

GET - create, show, edit and index.
POST - store
PUT/PATCH - update
DELETE - destroy

Each Controller file needs to be told which namespaces or Models to use.

Routing determines the URL mapping to actions that Controllers are to provide. Route can also be directly to a View or to deliver specific HTML contents without any Controllers.

The Laravel config directory contains a file, database.php with default settings to SQLite, Mysql and Postgresql database. You just need to fill in the appropriate values for the database in use. This Howto will use MySQL database.

Pre-Requisites

Installed the following and are in working order

  • Apache2
  • PHP v7.0.12
  • Composer 1.2.2
  • Lavarel 5.3


To install Laravel, refer to previous posting http://tboxmy.blogspot.my/2016/11/howto-install-laravel-framework-using.html

Step 1. Configure Lavarel to use MySQL

Create a database in MySQL called hellocustomer and assign the user permissions. Create 2 to 3 rows of dummy data as this howto will need to retrieve these data.

Edit the file hello/config/database.php and configure database

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'hellocustomer'),
            'username' => env('DB_USERNAME', 'mysql'),
            'password' => env('DB_PASSWORD', 'somepassword'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Edit hello/.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hellocustomer
DB_USERNAME=mysql
DB_PASSWORD=somepassword

Step 2. Create the Customer Model

1. At the project workspace directory, open a terminal and type

php artisan make:model Customer --migration

This will create

  • hello/app/Customer.php
  • hello/database/migrations/YYYY_MMM_DD_###_create_customers_table.php


2. Edit the table file in migrations (above) with all the required fields for Customer model.
3. Activate the migration file to generate Customer table in the database. Just type;

php artisan migrate

If the schema needs to be changed and database deleted after the above was created, just refresh the database, with;

php artisan migrate:refresh


Step 3. Create the CustomerController class

In order for the CustomerController class to retrieve data from the database, Eloquent provides the all() function, such as;
 $customers = Customer::all();  

An array of data rows are extracted to the variable $customers. No additional SQL coding is required.

At the terminal, type the following to generate the controller class app/Http/Controllers/CustomerController.php

php artisan make:controller CustomerController --resource

Edit CustomerController to use the Customer model by adding the "use App\Customer;" above class declaration as below;


use App\Customer;
class CustomerController extends Controller
{
 public function index()  
 {  
       //              
       $customers = Customer::all();  
       return View('customers.index')->with('cust', $customers);  
 }  

 public function show($id)  
 {  
       //              
       $customer = Customer::find($id);  
       return view('customers.show', array('customer' => $customer));  
 }  


Step 4. Create View for the Implemented Actions in Controller

Create a directory customers in resources/views and create the following 2 files

 <!DOCTYPE html>  
 <?php  
 // index.blade.php   
 ?>  
 <html>  
 <head>  
   <title>Customer index page</title>  
   <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">  
 </head>  
 <body>  
 Customers  
 <br/>  
 @foreach($cust as $key => $value)  
 <table>  
     <tr>  
       <td>{{ $value->id }}</td>  
       <td>{{ $value->cname }}</td>  
       <td>{{ $value->phone }}</td>  
                   </tr>  
                   @endforeach  
 </table>  
 </body>  

 <!DOCTYPE html>  
 <?php  
 // show.blade.php   
 ?>  
 <html>  
  <head>  
   <title>Customer</title>  
  </head>  
  <body>  
  <?php  
       if ($customer == null)   
       {  
             print "No data";  
             return;  
       }  
       ?>  
   <h1>Customer {{ $customer->id }}</h1>  
   <ul>  
    <li>Name: {{ $customer->cname }}</li>  
    <li>Phone: {{ $customer->phone }}</li>  
    <li>Last update: {{ $customer->last_update }}</li>  
   </ul>  
  </body>  
 </html>  

Edit routes/web.php file to use this new controller.

Route::resource('customer', 'CustomerController');

Step 5. Try them out

The Actions from our Laravel framework implementation can be listed with the command

php artisan route:list







Since you now know the URL for each Action we know to do the following displays for all customers and for each customer.

To call  INDEX action use the URL
http://localhost:8000/customers/



To call  SHOW action use the URL followed by a valid customer id.
http://localhost:8000/customers/1


Exercise:

This should take less than 15 minutes to complete.

Demonstrate use of database with Laravel. Create following Customer class below and display formatted data (create your own dummy data in the database).










No comments: