Understanding the Flow - Step 1 - A stripped back Request/Response example

There are a number of standard diagramatic approaches used to represent MVC diagrams. In the most common of these the Models, Views and Controllers are represented as three boxes with the User interacting with the Controller and being presented with information from the view. While this can be a useful way to look at the different components I prefer to use a UML sequence diagram to understand the flow of steps involved. Consider the following simplified example which describes a user filling in a html form which will allow for the creation of a new Customer in the system.

The user will interact with the system to indicate the desire to create a new Customer i.e. they will call the new( ) function of the CustomerController class. The Customer controller will call the view to generate the necessary html. The user will complete the form and submit which will call the create() function of the CustomerController. This then instantiates a new Customer Model object, sets the necessary attributes and saves the data.

To begin with, lets create the view. Use the following code snippet to create a file called new.blade.php in the tennisclub\resources\views\customers\ folder (note you will have to create the customers folder within the views folder first).

<FORM method="POST" action="/customers/create"> @csrf 
     Enter your first name:<input type="text" name="firstname"><br> 
     Enter your surname:<input type="text" name="surname"><br> 
     <input type="submit"> 
</FORM> 

Next we'll need to create the CustomerController. Use the following code snippet to create a file called CustomerController.php in tennisclub\app\Http\Controllers.

<?php 
namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use \App\Models\Customer as Customer; 

class CustomerController extends Controller 
{ 
    public function new() 
    { 
        return view('customers.new'); 
    } 

    public function create(Request $request) 
    { 
         echo "Firstname= " . $request->firstname;
         echo "<br>Surname= " . $request->surname;
    } 
} 
?> 

Before this example can work, we need to add routes to the web.php file in the routes folder which correspond to the new() and the create() actions.

Edit /tennisClub/routes/web.php and add the following lines

Route::get('/customers/new', 'App\Http\Controllers\CustomerController@new');
Route::post('/customers/create', 'App\Http\Controllers\CustomerController@create')->name('customers.create'); 

To try this example visit http://localhost:8000/customers/new. This will bring up the new.blade.php view. Fill in the details and click submit. This will in turn call the create( ) function of the customers controller. At this point all this will do is print the details you added to the screen. In the next step we'll see how to add the customer to the DB

Leave a Reply