Get up to 80 % extra points for free! More info:

Lesson 3 - The first application in Laravel

In the previous lesson, Installation of Laravel and first project run, we installed and got the Laravel framework up and running.

Today we will dive into the creation of the first simple application and explain its basic structure.

Application selection

One of the applications on which we can demonstrate the absolute basics and is very simple is the calculator, you can see the calculator on the screenshot below. I deliberately chose the calculator to start with because we won't have to worry about the database and configuration yet. Instead, we will briefly show you the most important components for development in the Laravel framework. We will deal with them in depth in the following lessons.

Calculator in PHP framework Laravel - Laravel Framework for PHP

Calculator creation

As we described in the first lesson Laravel is basically built on MVC architecture. We must also build on that now. So we start creating our calculator from the model to first create data for the view and methods, which the controller can then use immediately.

Model

We can easily generate the model via the command line / terminal in the folder with our project. In the command line opened in the project folder, insert the following command:

php artisan make:model Calculator

As we described in the first lesson, Laravel is basically built on MVC architecture. We must also build on that now. So we start from the model to create data for the view and methods which a controller can use then.

Model

We can easily generate the model via the command line / terminal in the project folder. open command line in the project folder and insert the following command:

php artisan make:model Calculator

The command to generate a model, as well as other commands that we will use today, has many options. For example, we can generate a CRUD controller for a given model. But since it is not important for us now, we will deal with it further in the course.

The generated model Calculator located in the app/ is as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Calculator extends Model
{
    //
}

The model in the Laravel framework in most cases represents a database table, so the models inherit from the Model class, which contains variables for defining various attributes and values and also provides us with object-relational mapping for working with the database. However, since our calculator will not be linked to the database, we can remove this inheritance.

We now define methods for 4 basic operations - addition, subtraction, multiplication and division. Our model will look like this:

<?php

namespace App;

/**
 * Calculator operation model.
 *
 * @package App
 */
class Calculator
{
    /**
     * Sum the given numbers and return the result.
     *
     * @param  int $a
     * @param  int $b
     * @return int
     */
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }

    /**
     * Subtract the second number from the first and return the result.
     *
     * @param  int $a
     * @param  int $b
     * @return int
     */
    public function subtract(int $a, int $b): int
    {
        return $a - $b;
    }

    /**
     * Multiply the given numbers and return the result.
     *
     * @param  int $a
     * @param  int $b
     * @return int
     */
    public function multiply(int $a, int $b): int
    {
        return $a * $b;
    }

    /**
     * Divide the first number by the second and return the result.
     *
     * @param  int $a
     * @param  int $b
     * @return int
     */
    public function divide(int $a, int $b): int
    {
        return floor($a / $b);
    }
}

Our calculator will be able to count only integer (whole numbers). We preserve this property even in division, so we return the result of division without remainder. And you may have noticed that we do not treat division by zero. We should treat this correctly in the model so that it can be reused at other points in the application. But we'll get to everything later.

I decided to count in whole numbers for simplicity (we do not have to round the decimal places of numbers, for example), but also because in the next lesson we will show the validation rules for the submitted data (via the form). One of them is the integer.

As you may have noticed, we used the so-called TypeHinting, which was added to PHP in version 7. I will use it only in this lesson and occasionally in other lessons due to dependency injection. I use it here because of the completeness of the OOP in MVC and also because we now want to count only in whole numbers.

We now have basic operations. However, the model should be extensible and according to MVC it is best not to change other components when changing the model. So we will add a simple interface to the class, which will provide us with these features. This means that we still define the following methods and constants:

/**
 * Definition of constants for operations.
 */
const
    ADD = 1,
    SUBTRACT = 2,
    MULTIPLY = 3,
    DIVIDE = 4;

/**
 * Return an array of available operations where key is the operation constant
 * and the value is the operation name.
 *
 * @return array
 */
public function getOperations(): array
{
    return [
        self::ADD => 'Addition',
        self::SUBTRACT => 'Subtraction',
        self::MULTIPLY => 'Multiplication',
        self::DIVIDE => 'Division',
    ];
}

/**
 * Call the passed operation with the defined constant and return its result.
 * If the operation does not exist, return null.
 *
 * @param  int $operation
 * @param  int $a
 * @param  int $b
 * @return int|null
 */
public function calculate(int $operation, int $a, int $b): ?int
{
    switch ($operation) {
        case self::ADD:
            return $this->add($a, $b);
        case self::SUBTRACT:
            return $this->subtract($a, $b);
        case self::MULTIPLY:
            return $this->multiply($a, $b);
        case self::DIVIDE:
            return $this->divide($a, $b);
        default:
            return null;
    }
}

We defined constants for individual operations, a method for returning all supported calculator operations with their labels, and finally a method for calculation, which starts the given calculation method according to the operation. In practice, of course, the individual computational methods would be longer and calculate something more complex, but this is enough for us as an example.

We are now able to easily add another operation to the model and do not need to modify other components in any way. If we inserted this solution e.g. directly into the controller, we would always have to edit 2 files when adding a new operation.

Although this may not seem to be the most ideal solution, this course is very sufficient and simple in our course. Thanks to this we can later show the features of other components, such as form validation.

Controllers

Now we will need an intermediary to show us the data. As we already know that a controller creates a model based on a request from the user and generates a view with data from the model. In the meantime, we will need the Calculator model and list possible calculator operations from it. We will keep the calculation and transmission of the result for the next time.

Now we can simply generate a controller called CalculatorController via the following command in the terminal / command line from the root folder of the project:

php artisan make:controller CalculatorController

The generated controller can be found in the app/Http/Controllers/ folder. The controller now contains only definition of a class called CalculatorController inherited from the Controller. Let's define a method for displaying a form with a calculator:

<?php

namespace App\Http\Controllers;

use App\Calculator;
use Illuminate\View\View;

class CalculatorController extends Controller
{
    /**
     * Display the calculator form.
     *
     * @param  Calculator $calculator
     * @return View
     */
    public function index(Calculator $calculator): View
    {
        return view('calculator', [
            'operations' => $calculator->getOperations(),
        ]);
    }
}

As you can see our method index() (action) for displaying a calculator form contains a $calculator parameter of type Calculator. The model instance in the parameter is obtained automatically thanks to the dependency injection. DI knows the instance of the class we want to pass according to the specified type. We simply ask what model we need.

Inside the method, we call only the helper function view() with two parameters. First one is to display a non-existent view called calculator.blade.php and the second one is an array with variables that are passed to the view. Now we have calculator operations available in the view. Let's create this view now.

View

We have to create the view manually in the resources/views/ folder. There we can also find a pre-created view called welcome.blade.php. Note that in addition to the view name and the .php extension, the file name also contains a .blade. This is how views using the Blade Template system are called. We have already described its basic functioning in the introductory lesson.

We will create our own view called calculator.blade.php with the following content:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
    </head>
    <body>
        <h1>Calculator</h1>

        <form method="POST" action="/calculator">
            Operation:
            <select name="operation">
                @foreach ($operations as $operation => $text)
                    <option value="{{ $operation }}">{{ $text }}</option>
                @endforeach
            </select>
            <br />

            First number:
            <input type="number" name="a" value="{{ $a ?? 0 }}" />
            <br />

            Second number:
            <input type="number" name="b" value="{{ $b ?? 0 }}" />
            <br />

            <button type="submit">Calculate the result</button>
        </form>

        @if (isset($result))
            <p>The result is: {{ $result }}</p>
        @endif
    </body>
</html>

The developers of the Laravel framework have decided in version 6.0.0 to move the styles and other things of the front-end part of the project into a special package. In order to simplify the first lessons, we will deal with this when we'll start working on a real web application.

If we go step by step, we will first create a POST form referring to /calculator route. We will create this route next time. In the form we then have a <select> element with the operations of our calculator. To list them, we will use the Blade notation @foreach (), which in the result is nothing more than an abbreviated version of <?php foreach (): ?> from PHP. To list the variable, we use the expression of double curly braces, ie {{ }}, which displays and secures the variable through the PHP function htmlspecialchars() against the XSS attack.

Next, we create two <input> elements for numbers. These input boxes display a variable with a number only if the variable exists. We will pass the variables later via the controller when processing the form, so this treatment is useful for us as we can use the same view for more actions. Specifically here also for the statement of the result when the form is sent.

Subsequently, the result is shown at the bottom of the page only if the variable $result exists. Again, we will use simple Blade notation for this, but this time it will be @if ().

We have reached the end of this lesson, see you next time :)

In the next lesson, Finishing the calculator in Laravel, we will complete the calculator by setting up the form submission and we also create a validation for the form. You will also be able to download its source code in case you have a problem with something.


 

Previous article
Installation of Laravel and first project run
All articles in this section
Laravel Framework for PHP
Skip article
(not recommended)
Finishing the calculator in Laravel
Article has been written for you by Lishaak
Avatar
User rating:
No one has rated this quite yet, be the first one!
Author is interested in programming mostly at web development, sometimes he does funny video edits from his vacations. He also loves memes and a lot of TV series :)
Activities