Database Seeding and Relationships using LARAVEL
Tags: laravel, webdev, beginners, tutorial
Published: 2022-10-26 14:18:36

Hi Fellas, In this blog, we'll walk through
1. How to create a table ( Migration ) and Model
2. Creating relationships between models ( Ex Library has_many Books ).
3. Seeding the database using the faker() library.

**Pre-requisite:**
1. PHP any version ( LTS is recommended )
2. Mysql ( for Database )
3. laravel

Let's get started !!!! whoooooeeeeeeee!!!! 🚀🚀

**STEP 1️⃣:**

- Let's create a new laravel project using the `laravel new demo` here demo is my project name

**STEP 2️⃣:**
- Change your current directory to the project created using the above command, in my case, it is `cd demo`. Ignore this line for professionals 😜
- Make sure you fill in the details in the .env file
- Create a database called demo by `create database demo;`

``` 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=demo ( create a database in MySQL called demo )
DB_USERNAME=your_mysql_usernamae
DB_PASSWORD=your_mysql_password 
```

- let's create two models 1. Ĺibrary 2. Books
 by `php artisan make:model Library -m `, `php artisan make:model Book  -m`
- -m creates the migration file where we can include the details about columns of the tables library and books 
- By executing the above commands laravel will create two files in the model and database directory.
```
database/migrations/2022_10_25_185618_create_books_table.php
database/migrations/2022_10_25_185530_create_libraries_table.php
app/Models/Book.php
app/Models/Library.php
```
**STEP 3️⃣:**
- Before running the migration command let's tell the laravel what are the columns that will be present in the model's created above 
- Let's get our hands dirty by writing some code now.
Add the below code in the `public function up()` method in the library and book the migration file 
``` 
// code to be added to the library migration file 
 Schema::create('libraries', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->string('librarian_name');
            $table->datetime('opening_time');
            $table->datetime('closing_time');
        });
// code to be added to the book migration file

 Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->integer('library_id');
            $table->timestamps();
            $table->string('name');
            $table->string('author_name');
        });
```

**STEP 4️⃣:**
- let's create or migrate the columns into the database by running `php artisan migrate`. You should see a log like this

![Laravel Migration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v5o9z8oauqia90hiz3ay.png)

**STEP 5️⃣:**

- Let us define the `has_many` relationship in the models ( Ex: Library has many books )

``` 
class Library extends Model
{
    use HasFactory;

    public function books()
    {
        return $this->hasMany(Book::class);
    }
}
```
**STEP 6️⃣:**
- Let's create and load the database with some dummy data by using seeder files.
- Create a factory file using `php artisan make:factory BookFactory --model=Book`
- Create a seeder file by `php artisan make:seeder BookSeeder`
- Add the following code to BookFactory.php file
```
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Book>
 */
class BookFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'library_id' => $this->faker->randomDigit(),
            'name' => $this->faker->text(),
            'author_name' => $this->faker->text(),
        ];
    }
}

```

- Add the following code to `BookSeeder.php` to create 10 records in the Books table  
``` <?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use \App\Models\Book;

class BookSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Book::factory(10)->create();
    }
}
 ```

- Finally Run the seeding command `php artisan db:seed --class=BookSeeder`

Similarly, we can write both Seeder and Factory files for the library model too. 


We can verify the data by running the select query from our database `select * from books`



![select query with mysql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y3po3n1c60jq14446h55.png)


**Entire code is present in GitHub repo**: https://github.com/SamalaSumanth0262/LARAVEL-Relationships-Seeding, Feel free to raise PR or contribute. we can add a hacktober-fest label too if required so that it counts towards the contribution

For those who don't know hacktober fest, No worries I was one of them 😜 https://hacktoberfest.com/


Please feel free to comment or any suggestions are welcome. Cheers !!!!!!!


You can get in touch with me on
Website🧑🏻‍💻: https://sumanthsamala.netlify.app/
Linkedin🗒: https://www.linkedin.com/in/samala-sumanth-82431161/
GitHub: https://github.com/SamalaSumanth0262
twitter: https://twitter.com/sumanth0262