Laravel — P27: Database Intro

Laravel Database Mastery: Starting Your Data Journey

Why database and not a model intro you may ask. A model is just class that communicates with a specific table in the database. I’m a true believer that you should understand a topic at a high level before you jump into creating code for it. Let’s take a moment to discuss the database and how Laravel interacts with it.

What is a Database?

It’s not going to be that type of basic article, but just so that we’re all on the same page, a database is a place where you store data. A database consists of tables and each table has records of information. I like to use the Excel analogy. An Excel Workbook (database) contains one or more sheets (tables) and each sheet contains content (records). We normally place headers for our sheets (columns) and we insert data into rows (also rows in db terminology).

Let’s step back out of Laravel and see how we create Databases and Tables with PHP. We can do this through various means, through phpMyAdmin or with a SQL command like: create database dino_test_db; but we really want to see how this looks like in PHP.

<?php
$server   = "localhost";
$username = "admin";
$password = "E9bIyRDwzidT";

$connection = new mysqli( $server, $username, $password );

if ( $connection->connect_error ) {
    die( $connection->connect_error );
}

$sql = "CREATE DATABASE dino_test_db";

if ( $connection->query($sql) === TRUE ) {
    echo "Database created successfully";
} else {
    die($connection->error);
}

echo "Connection established successfully";

Databases are easy to create. How about Tables?

<?php
$server   = "localhost";
$username = "admin";
$password = "E9bIyRDwzidT";
$database = "dino_test_db";

$connection = new mysqli( $server, $username, $password, $database );

if ( $connection->connect_error ) {
    die( $connection->connect_error );
}

$sql = "CREATE TABLE users (
            id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            first_name VARCHAR(255),
            last_name VARCHAR(255),
            email VARCHAR(255),
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
                       ON UPDATE CURRENT_TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($connection->query($sql) === TRUE) {
    echo "Table users created successfully";
} else {
    echo $connection->error;
}

echo "Connection established successfully";

That seems like a mess. You have to know quite a few SQL intricacies just to create a table.

Migrations

Laravel contains an amazing way to create database tables. You use migration files and then simply run the php artisan migrate command. We’re going to go into migrations in full later, but here’s an example:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

Models

A model is a class that communicates with the database table. The out of the box model that’s created with the php artisan make:model command comes with a ton of features that we’ll fully discuss in a later article. Here’s an example of a User model.

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * 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',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Each time that you want to add a new record, retrieve all records, update a record, or delete a record, you use the User model. You can run a command like return \App\Models\User::all(); to retrieve all users.

How can Laravel do this? With Eloquent, an object-relational mapper (ORM). It’s included with Laravel out of the box.

Factories and Seeders

We’re also going to discuss factories and seeders. A seeder is a class that contains data that will. be inserted into a specific table(s). Why do we need seeders? Sometimes we need to play around with data, like thousands of users, but we don’t want to manually enter it. So we let our seeder run a thousand times and generate a thousand records.

A factory is a class that can generate content for a seeder. The seeder will tell the factory, give me an array of data with first name, last name, and email. The factory generates a unique first name, last name, and email address and returns it back to the seeder. The seeder than inserts the data. You don’t have to write an array of 1000 unique users for the seeder to consume. Let the factory create it for you.

All of these modules work together on the database system. We’ll look at each in the next few articles.

Laravel Series

Continue your Laravel Learning.

Laravel — P26: Single Action Controllers

Simplifying Laravel: The Power of Single Action Controllers

Laravel – P26: Single Action Controllers

Optimize your Laravel application with single action controllers for focused functionality. Streamline tasks for efficiency & clarity.

Laravel — P27: Database Intro

Laravel Database Mastery: Starting Your Data Journey

Laravel – P27: Database Intro

Kickstart your Laravel project with a database intro. Unlock the secrets to managing data effectively for powerful, dynamic applications.

Evolving Your Laravel Projects: Mastering Migrations

Laravel – P28: Migrations

Ensure your Laravel database evolves with your app. Learn migrations for seamless updates and rollback capabilities. Start now!

Leave a Reply