Laravel E-Commerce Application Development – Admin Model and Migration

Laravel E-Commerce Application Development - Admin Model and Migration

Laravel E-Commerce Application Development ( 27 Lessons )

In this course, you’ll learn how to create an E-Commerce Website from scratch in Laravel. The process has never been easier I’ll take you from the very beginning stages of setting up Laravel till the last steps of adding products to the cart. If you’ve good understanding & experience in PHP & MySQL then this course is for you.

see full series
  1. Laravel E-Commerce Application Development – Introduction
  2. Laravel E-Commerce Application Development – Initial Project Setup
  3. Laravel E-Commerce Application Development – Assets Setup Using Laravel Mix
  4. Laravel E-Commerce Application Development – Admin Model and Migration
  5. Laravel E-Commerce Application Development – Backend Admin Authentication
  6. Laravel E-Commerce Application Development – Base Controller and Repository
  7. Laravel E-Commerce Application Development – Settings Section Part 1
  8. Laravel E-Commerce Application Development – Settings Section Part 2
  9. Laravel E-Commerce Application Development – Categories Section Part 1
  10. Laravel E-Commerce Application Development – Categories Section Part 2
  11. Laravel E-Commerce Application Development – Attributes Section Part 1
  12. Laravel E-Commerce Application Development – Attributes Section Part 2
  13. Laravel E-Commerce Application Development – Attributes Section Part 3
  14. Laravel E-Commerce Application Development – Brands Section
  15. Laravel E-Commerce Application Development – Products Section Part 1
  16. Laravel E-Commerce Application Development – Products Section Part 2
  17. Laravel E-Commerce Application Development – Products Section Part 3
  18. Laravel E-Commerce Application Development – Products Section Part 4
  19. Laravel E-Commerce Application Development – Frontend Login & Registration
  20. Laravel E-Commerce Application Development – Categories Navigation
  21. Laravel E-Commerce Application Development – Catalog Listing
  22. Laravel E-Commerce Application Development – Product Details Page
  23. Laravel E-Commerce Application Development – Shopping Cart
  24. Laravel E-Commerce Application Development – Checkout
  25. Laravel E-Commerce Application Development – Payment Processing
  26. Laravel E-Commerce Application Development – Order Management
  27. Laravel E-Commerce Application Development – Wrap Up

This is the third part of Laravel E-Commerce Application Development tutorial series, in this part we will set up Laravel Migrations and Seeds.

I assume you should have the e-commerce application project on your machine, we will start from where we left it in the last part. In the last part, we added the static assets for our project, now we will set up our Laravel migrations and seeds so we can start building the application.

Database Configurations and Some Fixes

First thing first, open you .env file and change the values of DB_DATABASE, DB_USERNAME and DB_PASSWORD to your ones.

If you want to use SQLite instead of MySQL then you have to change the DB_CONNECTION value to sqlite and remove all other DB_* entries. Also you will need to create a SQLite database file in the database folder named database.

I will be using MySQL so I make changes according to my machine.

Open AppServiceProvider from app/Providers folder and replace with the below one:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

Now as you know, Laravel provides a User model out of the box which resides in the app folder, I want to move this model file to Models folder so I will create a new folder called Models and move the file inside this folder. You will also need to change the namespace of User model class from App to App\Models.

As we have changed the location of the User model, we will need to make a minor fix in config/auth.php file. Find the providers array and change it with the below one.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

Once we have these fixes in place, we can start creating the models and migrations for our application.

Admin Model, Migration and Seed

In our application we want to have a separate login for our admin section and separate login for the customers, keeping this in mind we will add a new model called Admin. As I said earlier, Laravel comes with a User model which we will use for our customers, for the purpose of their login, registration and accounts management.

Now we will start creating the model, migrations, and seed for the Admin. Go to your terminal and run below artisan commands to generate the model, migrations and database seed.

php artisan make:model Models\\Admin -m
php artisan make:seed AdminsTableSeeder

Go to database/migrations folder and open admins migration file. Replace the up() function with the below one:

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

Now open the Admin model class (app/Models/Admin.php) and replace the whole class with the below ones.

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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

Now we will update the seeding class for our Admin model, for that open the AdminsTableSeeder class from database/seeds folder and replace with the below content:

use App\Models\Admin;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class AdminsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

        Admin::create([
            'name'      =>  $faker->name,
            'email'     =>  '[email protected]',
            'password'  =>  bcrypt('password'),
        ]);
    }
}

As you can see in this seed class we are adding the Admin model using the use keyword and also adding Faker to generat dummy names.

Within the run function of this class, we are creating a new instance of the Faker library by calling it’s create method. Next, we are creating a new admin entry with the information provided.

Adding Admin Seed to Database Seeder

Open the DatabaseSeeder class from within the database/seeds folder and add the below line in the run() function.

$this->call(AdminsTableSeeder::class);

This line will call our AdminsTableSeeder class when we run the db:seed artisan command and create database entries for us.

Running Migrations and Seed

Open your terminal and run the below command:

php artisan migrate --seed

After running this command, you will see the following output in the terminal.

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2019_05_16_084727_create_admins_table
Migrated:  2019_05_16_084727_create_admins_table
Seeding: AdminsTableSeeder
Database seeding completed successfully.

Now if you open your database and check the admins’ table, you will find a new entry was added to your admin table.

Final Word

In this part, we simply created the Admin model and migration with database seed. My plan was to create all models and migrations for our application, but I changed my mind to create models and migrations as we go. It will be easier for you to digest the information and I can explain each and every step.

Code Repository

You can find the code base of this series on Laravel eCommerce Application repository.

In the next part of this series, we will create the authentication for our Admin model to access the admin section of our application. We will also make sure only admins can access the admin section using the Laravel middlewares.

If you have any question about this post, please leave a comment in the comment box below.

17 comments on “Laravel E-Commerce Application Development – Admin Model and Migration

  1. For someone who is facing the class AdminstableSeeder does not exist:
    when running command php artisan migrate –seed an issue is coming that Class AdminsTableSeeder does not exist
    run composer dump-autoload to fix this and then run seeder command

    1. @said have you created the models folder in app and push user to it. Just like specified in step 2 of this tutorial

      1. You don’t need to manually create the folder, with de command line: php artisan make:model FolderName\ModelName if enough, if the folder doesn’t exist Laravel will create it.

  2. LaraShout, please can you guide how to make migrations and seed if I use mongoDb as DB?
    I’m interesting in using this NoSQL Database in this project. I hope you can give any idea, and don’t remove this comment. Thanks in advanced.

      1. Thanks for you reply, I started using the package you mentioned, but I would like you help me to clarify how to do the migrations and especially the seeders.

  3. For students, If you are running MySQL v5.7.7 and higher you do not need to do this in AppServiceProvider from app/Providers. “Schema::defaultStringLength(191); “.

  4. I totally agree with your final words in this article. I think you are a great teacher and all the readers of this series are lucky.

  5. hey, I am getting an Illuminate\Contracts\Container\BindingResolutionException : Target class [AdminsTableSeeder] does not exist error. Although I have followed the steps exactly. I tried running composer dump-autoload but running that doesnt help in getting rid of the error either.

Leave a Reply

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

*

When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.