Understanding the Flow - Step 3 - Passing Data to a View

While a View may need to display and present certain information it is not the View's job to go searching and retrieving information from the Model. The Controller can retrieve whatever information is relevant and pass that data along to the view for presentation.

There are a number of typical situations where it is necessary to pass data to a view:

  • A given object's data needs to be modified in some way - e.g. the customer changes their name and the surname needs to be modified
  • The view needs to present a set of options to the user which are populated from the database
  • The view needs to present some information to the user which is coming from the database

In each of these situations the relevant action function will likely retrieve the information and pass it to the view as a view variable or variables. The following diagram represents the flow of a retrieve customer - edit customer - update customer flow.

Add the following to get the edit($id) function working, add the following block of code to the CustomerController.php file in \app\http\controllers.

    public function edit($id)
    {
         $customer = Customer::find($id);
         return view('customers.edit')->with('customer', $customer);
    }

For the update part of the sequence add an update(Request $request) function

    public function update(Request $request)
    {
        $customer = Customer::find($request->id);
        $customer->setFirstname($request->firstname);
        $customer->setSurname($request->surname);
        $customer->save();
    }

Before we can proceed we need to create the view for the edit($id) function. Use the following code snippet to create a file called edit.blade.php in /tennisclub/resources/views/customers

<FORM method="POST" action="/customers/update"> 
    @csrf <input type="hidden" name="id" value="{{$customer->id}}"> 
    Enter your first name:<input type="text" name="firstname" value="{{$customer->firstname}}"><br> 
    Enter your surname:<input type="text" name="surname" value="{{$customer->surname}}"><br> <input type="submit"> 
</FORM> 

In addition we need to add two new routes to /tennisclub/routes/web.php file

Route::get('/customers/edit/{id}', 'App\Http\Controllers\CustomerController@edit');
Route::post('/customers/update', 'App\Http\Controllers\CustomerController@update');

Now, to edit the details of the customer you created in Step 2, visit http://localhost:8000/customers/edit/1

This should bring up the customer's details. From here you can edit the details and save. This should update the customers details in the DB.

Leave a Reply