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.


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.


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

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


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('', 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>  
 // index.blade.php   
   <title>Customer index page</title>  
   <link rel="stylesheet" href="//">  
 @foreach($cust as $key => $value)  
       <td>{{ $value->id }}</td>  
       <td>{{ $value->cname }}</td>  
       <td>{{ $value->phone }}</td>  

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

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

To call  SHOW action use the URL followed by a valid customer id.


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:

Blog Archive