Learning Management Platform for Written Tutorial Series.

Laravel 6 Form Processing

Laravel 6 Form Processing

Almost any application that you work with, in one way or the other you need to accept input from the users. On google search you type into a form to search for something, to login to your mailbox you fill in a login form. Making orders online needs forms too. These are just some of the examples of how we use forms in web applications.

In this tutorial, we will learn how to accept input from the users via forms and process the data on the backend. By the time that we are done, we would have created the following beautiful, simple and elegant application with full form functionality and complete source code.

Laravel 6 Forms

Topics to be covered

In this tutorial, we will cover the following topics

  • Laravel Form Basics
  • GET HTTP Verb
  • POST HTTP Verb
  • PUT HTTP Verb
  • DELETE HTTP Verb
  • Laravel Form Processing in Action

Laravel Form Basics

Processing forms in Laravel isn't very much different from working with forms in any PHP application generally. However, they are a few things that we must take into consideration when working with forms.

  • CSRF -- CSRF stands for Cross-Site Request Forgery which is an attack that forces the user to perform unwanted tasked in an authenticated application. Laravel has built-in mechanism that protect against this attack. Therefore, when processing forms, the appropriate csrf token must be set as well.
  • HTTP Verb -- as at now, most web applications support GET and POST out of the box. PUT and DELETE verbs are usually used in APIs mostly. Laravel enables us to fake these methods within the web browser and the backend responds to them accordingly.

The rest of the stuff is exactly the same as in any other application. We will cover them as we proceed with the tutorial.

HTTP Verbs

Hypertext Transfer Protocol Verbs are used to determine the action that should be taken when a resource is been requested. A GET request will return a resource while a POST request usually creates a new resource. These verbs help us to create uniform resources whose actions are determined by the specified HTTP verb.

GET HTTP Verb

This is the most commonly used HTTP Verb. As stated in the above section, GET is used to retrieve resources. When working with forms, GET is mostly used for search purposes and the results returned can be bookmarked. Any data submitted using GET is visible in the URL so never use it when processing sensitive data such as user passwords when logging in. GET is supported out of the box by the web browser.

POST HTTP Verb

This verb is used to create new resources. It is also supported out of the box by web browsers. It can be used when authenticating users, and creating new resources i.e. new records in the database. The values submitted using POST verb are not visible in the URL.

PUT HTTP Verb

This verb is used to update existing resources. For example, if you want to update a customer record in the database, you can use PUT when submitting the data to the backend for processing. This is not supported out of the box by most web browsers but thanks to Laravel, we can fake it and the backend won't know the difference.

DELETE HTTP Verb

As the name suggests, this verb is used to delete existing resources. Just like PUT verb, it too is not supported out of the box by most web browsers. In Laravel framework, it can be faked.

Other HTTP Verbs

Other HTTP verbs include PATCH, TRACE, CONNECT, and OPTIONS but for purposes of this tutorial, we will only look at GET, POST, PUT and DELETE.

Laravel Form Processing in Action

Now that we have covered the basic theories behind form processing in Laravel, it's time to get our hands dirty.

Let's create a new Laravel project. Run the following artisan command

composer create-project laravel/laravel forms 6.0.\*

HERE,

  • The above command creates a new Laravel project using latest version of Laravel 5.8

Next we will create a resource controller. A resource controller is a controller that comes with boilerplate code for the four HTTP verbs GET, POST, PUT, DELETE and a couple of methods for displaying forms.

Run the following command

php artisan make:controller PersonsController --resource

Open the controller /app/Http/PersonsController.php

You will be able to see the following methods

  • index(){...} this method is usually used to retrieve all the resources from the server and display them in the browser. It works with the GET verb
  • create(){...} this method is used to display a create new resource form. It works with the GET verb
  • store(Request $request){...} this method is used to create a new resource then usually redirect to the index method. It works with the POST verb
  • show($id){...} this method is used to retrieve an existing resource and display its values in read-only form. It works with the GET verb.
  • edit($id) this method is used to retrieve an existing resource and load the values in the form for editing. It works with the GET verb.
  • update(Request $request, $id) this method is used to update the existing resource then redirect to either the index or show method. It works with PUT verb.
  • destroy($id) this method is used to deleted an existing resource. It works with the delete verb.

For the sake of simplicity and focus, we will skip the database interaction part in this tutorial. The database interaction is covered in another tutorial on our site.

Update the controller methods to the following.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PersonsController extends Controller
{
    public function index()
    {
        $persons = [
            [
                'id'         => 1,
                'first_name' => 'John',
                'last_name'  => 'Smith',
            ],
            [
                'id'         => 2,
                'first_name' => 'Jane',
                'last_name'  => 'Smith',
            ],
        ];

        $params = [
            'title'   => 'Persons Listing',
            'persons' => $persons,
        ];

        return view('persons.index')->with($params);
    }

    public function create()
    {
        $params = [
            'title' => 'Add Person',
        ];

        return view('persons.create')->with($params);
    }

    public function store(Request $request)
    {
        return redirect()
            ->route('persons.index')
            ->with('status', 'New person successfully created!');
    }

    public function show($id)
    {
        $person = [
            'id'         => 1,
            'first_name' => 'John',
            'last_name'  => 'Smith',
        ];

        $params = [
            'title'  => 'Person Details',
            'person' => $person,
        ];

        return view('persons.show')->with($params);
    }

    public function edit($id)
    {
        $person = [
            'id'         => 1,
            'first_name' => 'John',
            'last_name'  => 'Smith',
        ];

        $params = [
            'title'  => 'Person Details',
            'person' => $person,
        ];

        return view('persons.edit')->with($params);
    }

    public function update(Request $request, $id)
    {
        return redirect()
            ->route('persons.index')
            ->with('status', 'Person details successfully updated!');
    }

    public function destroy($id)
    {
        return redirect()
            ->route('persons.index')
            ->with('status', 'Person record successfully deleted!');
    }
}

HERE,

  • $persons = [...] this array variable simulates database records so that we can display something in our application.
  • $person = [...] this array variable simulates a single person record that we are using in editing and show record forms.
  • return redirect()... returns the user to the persons index page after the record has been created, updated or deleted.

Note: We have deliberately skipped the actual database creation process in our methods for the sake of simplicity.

Laravel Form Processing Blade Views

In this section, we will first examine the anatomy of forms in Laravel then create the blade views for our example project.

The basic form setup in Laravel should be as follows

<form action="{{route('routename',['param' => 1])}}" method="POST">
	@csrf
    @method('PUT')
    <!-- Input tags go here -->
    <button class="btn btn-info" type="submit">
        <i class="fa fa-save"></i> Update Person Details
    </button>
</form>

HERE,

  • action="{{route('routename',['param' => 1])}}" in the action section, it's better to use named routes because if it changes then you don't have to update your forms.
  • method="POST" since we are faking PUT and DELETE, we still have to use POST verb to fool the browser then use the method directive
  • @method(\'PUT\') this blade directive sets the HTTP verb that the backend server will respond to.
  • @csrf is a Blade directive that adds the csrf token that Laravel verifies before processing the form.

For the sake of brevity, we have not included the views in this tutorial but you can download them from the Github repository of this tutorial

Laravel Form Processing Resource Route

We will now create a resource route. A resource route maps a single route to all of the methods in the controller that we created in the above section.

Open /routes/web.php

Add the following code

Route::resource('persons', 'PersonsController');

HERE,

  • The above creates a links to the resource persons that are bound to PersonsController

That's it for our controller.

Run the following command to display the registered routes in our application

php artisan route:list

you will get the following routes

Laravel 6 Resource Routes

Note: Our persons resource is mapped to the methods in the resource controller and has automatically figured out the correct HTTP verbs.

You can now take the application for a spin

Run the following command to start the built-in server

php artisan serve

Load the following URL

http://localhost:8000/persons

Laravel Forms

Click on the Add New Person Button

You will get the following window

Laravel 6 Forms Add

Fill in the details and click on Add New Person

You should be redirected to the home page with the following status message

Laravel flash message

Try clicking on the eye symbol to show the record details

Laravel 6 Forms Delete

Click on delete person button

You should be able to see the following page after been redirected.

Laravel Delete Flash Message

Click on edit button

Laravel 6 Forms Edit

Click on update button. You should be able to see the following message

Success Flash Message

Summary

In this lesson, we covered the basics of HTML forms processing in general then looked at the features that are unique to Laravel and what extra capabilities that Laravel framework brings to the table. We also demonstrated the capabilities using a practical example. If you have any questions, use the comments section. If you have no questions we still would hear to get your views in the comments section.

What's next?

In this tutorial, we simply displayed records and assumed the users entered the correct parameters. The next tutorial will build on this


...