Understanding the Flow - Step 2 - Adding a Model Class

In this step we are going to make the customer data save to the database. For this we will need a database table called customer. Execute the following SQL code on your tennisclub database to create a customer table.

create table customer (
  id int auto_increment,
  firstname varchar(30),
  surname varchar(30),
  primary key(id)
);

In  a simple traditional PHP application, processing the data might mean gathering the data from the form and inserting it into the database through the use of a MYSQL "Insert into" command. Leaving aside connecting to the database and stripping it back as far as possible the code might look something like this.

$fname = $_POST['firstname'];
$sname = $_POST['surname];
$sql = "insert into customer values('$sname','$fname')";
$mysqli_execute($dbcon,$sql);

Using an MVC approach, we don't use any SQL directly as the insertion of data into the database is handled by Object Relationship Mapping. The equivalent functionality is achieved using code which looks like the following:

$customer = new Customer(); //creates a new instance of the customer object
$customer->setFirstname($request->firstname);//sets the attributes
$customer->setSurname($request->surname);//sets the attributes
$customer->save();//persists the Customer object to the database

The following is a simple stripped back model class which will process and store information about customers in our simple example. Use the code snippet below to create a file called customer.php in the tennisclub\app\models folder.

<?php 
namespace App\Models; 
use Illuminate\Database\Eloquent\Model as Model; 

class customer extends Model 
{ 
    public $table = "customer"; 
    public $timestamps = false;
    
    public function setFirstname($fn) 
    { 
        $this->attributes['firstname']=$fn;
    } 

    public function setSurname($sn) 
    { 
        $this->attributes['surname']=$sn; 
    } 
} 
?>

Modify the create( ) function of the customer controller from Step 1 so that it now appears as follows:

public function create(Request $request)      
{
    //instantiate a new Customer object from the Model class
    $customer = new Customer();
    //call setter on the object passing values from the View
    $customer->setFirstname($request->firstname);
    $customer->setSurname($request->surname);
    //save the object which will create a new customer in the DB
    $customer->save();        
}  

Now when you submit the form data will be stored in the database.

Leave a Reply