← Other topics

Laravel In a Nutshell - Eloquent Models & Seeding (#6)

Series contents:

Video Notes

There’s a few different ways you can interact with your database in Laravel, but the primary approach is to use something called Eloquent. Eloquent is an ORM, or object-relational mapper, which maps PHP classes to tables in our database. These database-specific PHP classes are referred to as Models and they give us the ability to create, read, update, and delete data from our tables.

To get started, we can use Artisan to generate a Model called Product for our products table:

> php artisan make:model Product

And also a Category Model for our categories table:

> php artisan make:model Category

Your Model classes will be found in the directory /app/Models.

Note that the expected convention in Laravel is that your table names are always written all lowercase and plural, while the corresponding model is capitalized and singular. You can overwrite this convention if necessary but it’s easiest to just follow it whenever possible.

Defining relationships in models

Within your Model classes, you want to define relationship methods that make the Models aware of each other. This will help simplify the database queries you write.

For example, in the Product model, add a categories method as shown below:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Product extends Model
{
    use HasFactory;

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }
}

Likewise, add a products method to your Category Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Category extends Model
{
    use HasFactory;

    public function products(): HasMany
    {
        return $this->hasMany(Product::class);
    }
}

The above example sets up a BelongsTo and HasMany relationship, which are just two the relationship types you might encounter. Check the docs for a complete list of relationship types that Eloquent provides: Eloquent: Defining Relationships.

Seeding

With everything set up, let’s now practice interacting with the database via our Models starting with the ability to create rows in our database tables.

To demonstrate this, we’ll work within Laravel’s Seeding feature which provides a way to seed our database tables with initial test/development data.

Open the file database/seeders/DatabaseSeeder.php and edit it to match the following code:

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Product; # ⭐ ADD THIS LINE
use App\Models\Category; # ⭐ ADD THIS LINE

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        # Create a new category
        $category = new Category();
        $category->name = 'health';
        $category->save();

        # Query for all the categories and output them as an array
        dump(Category::all()->toArray());

        # Create a new product associated with the above category
        $product = new Product();
        $product->name = 'Band-Aids';
        $product->category_id = $category->id;
        $product->save();

        # Demonstrate how we can access the category to product relationship
        dump($product->category->name);
        
        # Query for all the products and output them as an array
        dump(Product::all()->toArray());
    }
}

To execute the above code run:

> php artisan db:seed

If you run it multiple times, you’ll get the same product and category entered multiple times. To give your database a fresh start eliminating any duplicate seed data, run:

> php artisan migrate:fresh --seed

Adding all the categories and products

Now that we understand the basics of working with Models to insert new data, we can put together some code that will add all the categories and products data from our $productsByCategory array:

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Product;
use App\Models\Category;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $productsByCategory = [
            'health' => [
                'Band-Aids',
                'Johnson’s Baby Powder',
                'Tylenol'
            ],
            'tech' => [
                'GoPro Action Camera',
                'FitBit Fitness Watch',
                'Nintendo Switch'
            ],
            'books' => [
                'The Martian',
                'The Great Gatsby',
                'Joy Luck Club'
            ]
        ];

        foreach($productsByCategory as $categoryName => $products) {
            $newCategory = new Category();
            $newCategory->name = $categoryName;
            $newCategory->save();
        
            foreach($products as $product) {
                $newProduct = new Product();
                $newProduct->name = $product;
                $newProduct->category()->associate($newCategory);
                $newProduct->save();
            }
        }
    }
}

Conclusion

In the above example we saw how we can use Models (PHP classes designed to interact with our database tables) to insert new data. We did this via Laravel’s Seeder system as a way to fill our database tables with some test data. Of course, Models can also be used to read, update, and delete data.

In the next part of this series, we’ll put Models to use within our application to retrieve and show database data on the page.

If this info helped you out you can say thanks and support future content by clicking my Amazon affiliate link: https://amzn.to/3UtgnYk. If you make a purchase on Amazon within 24 hours of clicking the link I may receive a micro-commission and it costs you nothing extra. Any income from these sales goes directly to supporting me in making new videos and guides. Thank you for your support!

← Other topics