© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. SahuPHP 8 Basicshttps://doi.org/10.1007/978-1-4842-8082-9_14

14. Introduction to Laravel

Gunnard Engebreth1   and Satej Kumar Sahu2
(1)
Madison, WI, USA
(2)
Bangalore, India
 

Lately the development of web applications and websites has become more and more simple as developers make use of development tools. Let’s explore which PHP framework can support web developers when building new web projects and applications.

In this chapter, you will focus on the Laravel PGP framework, which is a very popular web application framework that is easy to use and offers an elegant syntax. It helps you with common tasks such as a fast routing engine, real-time event broadcasting, database-agnostic schema migrations, and more.

This chapter consists of the following sections:
  • Introduction to Laravel

  • Installing Laravel

  • Database Setup and Configuration

  • Database Migrations

  • Controller Route

  • Registration View Form

  • Storing User Data in a Database

Introduction to Laravel

Laravel is a modern PHP framework based on the MVC design pattern. An excerpt from the website explains it the best: “Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation—freeing you to create without sweating the small things.”

Installing Laravel

There are many ways Laravel can be installed. They can be found at https://laravel.com/docs/9.x/installation#your-first-laravel-project.

You will be following the simplest one to get you up and running. Please make sure these prerequisites are installed before proceeding:
  • PHP

  • Composer

To start a new project with the name of blog-app, run the following command:
composer create-project laravel/laravel blog-app
The project structure looks like Figure 14-1 without the .git directory.
Figure 14-1

Laravel project directory structure

Let’s explore the common parts of the directory.

Once the project has been created, start it using the following commands:
cd blog-app
php artisan serve
You can now access the app at http://localhost:8000, as shown in Figure 14-2.
Figure 14-2

Laravel main web page

This should confirm a valid installation and setup of Laravel.

Database Setup and Configuration

You will learn about the various components of Laravel as you build one sub-part of your blog application, which is user registration. Along the way, you will see how Laravel makes it easy for you to build such an application.

The core of any application is data, and you will need a database to store data related to your users.

You will create the table in an incremental fashion as you proceed through the different steps. In previous chapters you created the database and tables manually, using the phpMyAdmin interface. This usually works for a demo project, but while working on a production project, it is suggested to maintain databases and tables in migrations, which are stored in files and can be committed to source code management systems like git.

This helps to have a repeatable data structure that can be readily used by other team members to get quickly onboarded and set up the project and also to create different environments for running projects like dev, staging, and production. An added benefit is having a versioned schema of your database and tables to understand and maintain the history of changes for auditing and other such purposes.

Before you start setting up the migration aspect of Laravel, you must configure the database configuration settings. They can be found in the file config/database.php. Let’s review the contents of this file.
'default' => env('DB_CONNECTION', 'mysql'),
The default connection uses the mysql adapter, which suits your setup. Reviewing the connections section, you see the configs specific to the mysql connection.
'connections' => [
        'sqlite' => [
            ...
        ],
        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', ''),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
The url, host, and port values are taken from the .env environment file. This is a good practice, rather than hard-coding the secret values in scm. To set the right values, open up .env file in the project root. You will find the following section:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Once updated, make sure to clear the cache and update the config cache with this change by running the following commands:
php artisan cache:clear
php artisan config:cache
The output is shown in Figure 14-3.
Figure 14-3

Laravel cache cleaning command output

Replace DB_DATABASE with your blog value and also set a DB_USERNAME and DB_PASSWORD relevant to your MySQL setup.

Database Migrations

Laravel provides a command to create migrations:
php artisan make:migration <identity_name_for_operation>
You will create a table called users to store user data. Run the following command to accomplish this:
php artisan make:migration create_users_table --create=users --table=users
The output is shown in Figure 14-4.
Figure 14-4

Laravel DB table creation

The create and table options suggest creating a table in the database and the name of the table.

On running git status, you’ll see a new file created at database/migrations/2022_07_31_095213_create_users_table.php. The name may be similar for you, except the prefix, which adds a timestamp value to it. This does not create the table yet in the database. Let's review the contents of this file.
2022_07_31_095213_create_users_table.php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};
From this default template, you can see two functions named up and down. up is used to execute the current change in a migration and down is used to revert the change. Inside the up function you can see the create call with two fields, id and timestamps. Let’s execute the migration to see the change reflected in your database. Before running the following command, please make sure to remove any preexisting migration files that might have come with the initial setup in the database/migrations directory. Also, make sure your vendor/laravel/sanctum/database/migrations directory is empty too.
php artisan migrate
The output is shown in Figure 14-5.
Figure 14-5

Laravel migrating output

Refreshing your tables in phpMyAdmin shows two tables, as shown in Figure 14-6.
Figure 14-6

Laravel table refreshing output

The migrations table is a Laravel-specific table created to track the migration changes. Figure 14-7 shows a quick look at the migrations table schema, which specifies the one migration you did just now.
Figure 14-7

List of tables

Reviewing the users table schema shown in Figure 14-8, you see that it has a primary key id and two timestamp fields. You may need a few more fields like name, email, and password. You’ll add them in following section.
Figure 14-8

Laravel table schema

Create a new migration file as follows:
php artisan make:migration update_users_table --table=users
The output is shown in Figure 14-9.
Figure 14-9

New migration file

Open the new migration file in the database/migrations directory, which looks like the following:
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
};
Let’s update the up method to contain the changes you want to bring in this migration and the down method with the reverse changes so as to remove them in case of a rollover:
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('name');
            $table->string('email');
            $table->string('password');
        });
    }
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('name');
            $table->dropColumn('email');
            $table->dropColumn('password');
        });
    }
Now run the migrations:
php artisan migrate
The output is shown in Figure 14-10.
Figure 14-10

Laravel migrating output

On revisiting the table schema, it has your changes. See Figure 14-11.
Figure 14-11

Changes in the table schema

Since the users table is set up, you can now create the user registration feature. There are three subfeatures of it functionality-wise that you will build:
  1. 1.

    Controller route to load the registration view form and accept form submit requests

     
  2. 2.

    Registration view form

     
  3. 3.

    Store user data in a database

     

Controller Route

When you visit http://localhost:8000/register, you get the page displayed in Figure 14-12, which is 404 not found, since you do not yet have a route for this URL in your controller.
Figure 14-12

Laravel not-found page

On opening routes/web.php you see the following content:
<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});

Let’s create a sample view page file in the resources/views/ directory named register.blade.php and set its content as follows to start with:

Registration Page

To load this page, add a route for the /register path as follows in routes/web.php file:
Route::get('/register', function () {
    return view('register');
});

Inspecting this code, it is evident that get specifies the REST API verb and /register the relative URI path for the get request. When the controller intercepts a get request to the /register path, it will return the register.blade.php page through a call to view('register').

Save the file and then visit http://localhost:8000/register and you should see the output shown in Figure 14-13.
Figure 14-13

Registration page

You will develop the registration form later. For now, let’s create a sample view page for the registration success page and the other route for accepting the form submit request for registration submission.

The registration success page is at resources/views/registration_success.blade.php.
You have been successfully registered!
The following code should be added to routes/web.php:
Route::post('/register', function () {
    return view('registration_success');
});

The above route is for a post route request sent to the /register path and it returns the registration_success page. You will process the data later.

To test this change, either open a terminal with the curl command or Postman. Postman is a UI interface to run API requests. Further documentation related to its installation and usage can be found at https://learning.postman.com/docs/getting-started/introduction/.

curl request:
curl --location --request POST 'http://localhost:8000/register'
The output is shown in Figure 14-14.
Figure 14-14

curl request comment output

The Postman request is shown in Figure 14-15.
Figure 14-15

Postman request output

The output should load 419 | Page expired. This is a security mechanism which expects a csrf token. We will go into more details when you build the registration form. This output should verify that at least your POST route for the register works.

Registration View Form

Laravel's blade engine provides many built-in features to load, loop, parse data, and use in-built functions as needed. You will learn how to create a form that takes as input a few fields and submits them to your /register POST route.

To add form capabilities, install the following package, which has this feature, by running this command:
composer require laravelcollective/html
You make changes to the view file at resources/view/registration_success.blade.php by adding
Registration Page
{{ Form::open(array('url' => 'register')) }}
    // Form fields
{{ Form::close() }}
This creates a basic form HTML element with a form action URL set to the /register route and a csrf token for XSS protection, as you can see from the dev tools inspection in Figure 14-16.
Figure 14-16

Updated registration page

Next, let’s add a few fields that a user should fill in when registering.

1. Name field
{{ Form::label('name', 'Name'); }}
{{ Form::text('name'); }}
2. Email field
{{ Form::label('email', 'Email'); }}
{{ Form::email('email', $value = null, $attributes = array()); }}
3. Password field
{{ Form::label('password', 'Password'); }}
{{ Form::password('password'); }}
4. Submit button
{{ Form::submit('Register'); }}

These field elements should be added between the Form::open and Form::close calls.

The final view page code should like the following:
Registration Page
<br/>
<br/>
{{ Form::open(array('url' => 'register')) }}
{{ Form::label('name', 'Name'); }}
{{ Form::text('name'); }}
<br/>
<br/>
{{ Form::label('email', 'Email'); }}
{{ Form::email('email', $value = null, $attributes = array()); }}
<br/>
<br/>
{{ Form::label('password', 'Password'); }}
{{ Form::password('password'); }}
<br/>
<br/>
{{ Form::submit('Register'); }}
{{ Form::close() }}
Reloading the page should show output like Figure 14-17.
Figure 14-17

Refreshed registration page

Try filling in the field details with some sample values and click the Register button to see the form POST submit request in action. On submitting, it will look like Figure 14-18.
Figure 14-18

Successful registration page

Storing User Data in a Database

You have the view and controllers set up, but you are not yet doing anything with the data. One of the important parts is to parse the POST request-submitted data, validate it, and then save it to the database. To keep it simple, you will only parse the data and save it to the database. Note that validation is very important before processing user-submitted data.

Now that you have been able to post data to a route end, you will parse the different values. These values are available as part of the Request object passed to the route method. Let’s see it in practice. Make the following changes to the post route method in routes/web.php:
use IlluminateHttpRequest;
....
Route::post('/register', function (Request $request) {
    return view('registration_success');
});

Different values can be accessed by accessing properties on the $request object. For example, to fetch the email value, use $request->email. Now you know how to parse the different post parameters, so you can proceed to using these values to save them in database.

Laravel uses Eloquent, which is an object relational mapper (ORM), which makes it very flexible to interact with databases. With this approach, each table has a respective model that is used to interact with that table.
Eloquent reference: https://laravel.com/docs/9.x/eloquent
ORM: https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping
Let’s create a model for your user table at app/Models/User.php with the following command:
php artisan make:model User
The output is shown in Figure 14-19.
Figure 14-19

Model creation output

If you want to create a migration file at same time, please add the --migration option.
php artisan make:model User --migration
This creates a file at app/Models/User.php with the following default template:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class User extends Model
{
    use HasFactory;
}
To add more fields, such as name, email, and password, add the following code to the class body:
   /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
    ];
Now your User model is ready to be used. To use the User model in your controller, update routes/web.php with the following namespace to declare the User model:
use AppModelsUser;
....
Route::post('/register', function (Request $request) {
    User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password)
    ]);
    return view('registration_success');
});
This will save the user details in the user table and return the registration success template to the user. Notice you are using the Hash helper to one-way hash the password so that the password is stored in an encrypted format in database for security purpose. The output is shown in Figure 14-20.
Figure 14-20

Updated registration output

Let’s also check the database for the user details stored with an encrypted password, as shown in Figure 14-21.
Figure 14-21

Laravel DB encrypted password

Summary

In this chapter, you went through the essential elements to get started with Laravel. You explored some of the main Laravel features but in general there are many more that you will find handy, along with a plethora of packages that are present in the Composer repository. Always check the documentation of Laravel to see if there is an existing component, helper, or library that can helps you with your task before checking the Composer libraries or creating a custom library. This will save you a lot of time in terms of development and maintenance. Laravel is continuously improving, so always follow Laravel news, email lists, and newsletters to stay up to date.

In the next chapter, you will focus on another PHP framework named Symfony, which is a very popular PHP framework already used by thousands of web applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset