Laravel Model and Database

By Rasyue | On November 7, 2020

In this tutorial which is part of the Laravel For Beginners Series, we are going to learn about Model and Database in Laravel.

We will learn how to create a Model, table and stuff. For the database, we will be using both MySQL and MongoDB

Introduction

Laravel uses the architecture pattern MVC or also known as Model-View-Controller.

If you are still confused or having problem understanding the MVC pattern in Laravel, I strongly suggest that you read my previous post, Laravel: MVC Pattern.

Connecting to Database (MySQL)

Laravel comes with a very simple way to help you to connect to database.

Currently Laravel supports up to 4 kind of DBs which are MySQL, SQL Server, PostgreSQL and SQLite. But we are going to be using MySQL in this tutorial.

Now, go to your .env file which is in the root folder.

laravel rasyue

In the yellow highlights are where you will define your database connection information.

If you are a beginners or if you are still confused on how you can have MySQL installed on your computer, I strongly suggest that you have XAMPP installed.

There are other ways you can have MySQL installed but I find that XAMPP is the quickest way for you to not only have access to MySQL but also PHP and other stuff.

To make things easier you can see below db credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=rasyuelaravel
DB_USERNAME=root
DB_PASSWORD=

And that is all you need to do to connect your Laravel app to MySQL.

Make sure you have your mysql running.

Moving along.

Laravel Model

First of all, to create a model in Laravel, simply run the following command in your command prompt.

php artisan make:model Courses

Of course, you can replace the Courses with any name that you like.

I name my model Courses because I would like to create a table that stores all data related to courses (like course’s name, time, length, owner etc).

The command will create a new file under app/Models/ which is name Courses.php or whatever name you used earlier.

If you open your model file, you can see that the class is empty, I have went ahead and fill it in with a few configs.

<?php

namespace App\Models;

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

class Courses extends Model
{
    use HasFactory;

    protected $table = 'my_courses';

    protected $primaryKey = 'id';

    public $timestamps = false;

    protected $fillable = [
        'name',
        'type'
    ];

}

Laravel Model Migration

With Migration in Laravel, you don’t have to go to your MySQL manager and have create the table one by one.

Instead you can create a migration, one per each table, and by running the laravel command, laravel will automatically create the table for you.

This is really great for version control.

Run the below command to create the migration file first.

php artisan make:migration create_courses_table

You can replace the create_courses_table with anything that correspond to the table that you want to create.

Open the file that is newly created under database/migrations.

laravel rasyue

I have went ahead and modified my migration file for courses.

You can see that in the function up(), the schema will create the table and you can specify any number of columns that you want.

In this case, I have 3 columns/fields which are id, name and type.

Run the below command to run the migration.

php artisan migrate

And with that, you can check in your MySQL to see if the table has been created.

Laravel Model Seeding

With Laravel Seeding, you can quickly create some fake data in your table.

This is totally optional, if you feel like you need some data in your table then you may do so.

If not, just skip this step.

First, we will need to create the Seeder file. Run the following command.

php artisan make:seeder CoursesTableSeeder

This will create a new file under database/seeders. Open the file.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class CoursesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\Courses::factory()->count(10)->create()->each(function ($course) {
            $course->save();
        });

    }
}

Make sure the content of the file is the same as above.

Notice the count(10). You can specify any number you like to replace the value 10.

Laravel Factory

To create a factory file, run the following.

php artisan make:factory CoursesFactory --model=Courses

Open the file under database/factories and paste the following.

<?php

namespace Database\Factories;

use App\Models\Courses;
use Illuminate\Database\Eloquent\Factories\Factory;

class CoursesFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Courses::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'type' => $this->faker->name           
        ];
    }
}

Notice that in the function definition(), I have specified two key namely as name and type. Change accordingly to match your fields’ table.

Then run the following command to input the fake data.

php artisan db:seed --class=CoursesTableSeeder

Change the CoursesTableSeeder following to your seeder’s Class.

Check your table and you should be seeing some data.

The End..

In the next tutorial of the Laravel For Beginners Series, we will learn how to set up authentication in Laravel.

See you in the next tutorial!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*