Laravel E-Commerce Application Development – Categories Section Part 1

Laravel E-Commerce Application Development – Categories Section Part 1

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 eighth part of the Laravel E-Commerce Application Development series, in this part will add the model, migrations and model factory for categories section.

I assume you should have the e-commerce application project on your machine or you can grab it from Laravel E-Commerce Application repository, we will start from where we left it in the last part.

In this post, we will create a category model, migration, seed, and factor to our application.

So let’s start some coding.

Creating Category Model and Migration

To save our product categories to the database, we will need to create model and migration which will create a table in the database. Open your command line terminal and run the below command to generate the model and migration for categories.

php artisan make:model Models\Category -m

This command will generate a Category model in app/Models folder with migration file in database/migrations folder.

Open your migration file and update with the below one.

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

class CreateCategoriesTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('categories', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

As you can see we are adding various columns for our categories table. We are adding name, slug, description and image columns which you might have in any model of your application.

We are also adding the parent_id column, where we will store the parent category id to make a nested tree of categories. Next, we have added a featured column with boolean type, based on this, we will show the featured categories on our homepage. The menu field will provide us some control to show or hide a category in the main navigation of our website.

Now open, your Category model and define the $fillable and $cast properties like below.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
    protected $table = 'categories';

    protected $fillable = [
        'name', 'slug', 'description', 'parent_id', 'featured', 'menu', 'image'

    protected $casts = [
        'parent_id' =>  'integer',
        'featured'  =>  'boolean',
        'menu'      =>  'boolean'

Creating Category Seed and Factory

Next, we will add the database seed class and a model factory class for quickly generating dummy data. Run the below two commands in the terminal to generate seed and factory.

php artisan make:seed CategoriesTableSeeder
php artisan make:factory CategoryFactory --model=App\Models\Category

Above commands will generate the database seed in database/seeds folder and a factory class in database/factories folder.

Learn More

You can learn more about how to generate dummy data in Laravel by reading our post Using Laravel Model Factories To Generate Dummy Data.

Open the CategoriesTableSeeder class and add the below content in this class.

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

class CategoriesTableSeeder extends Seeder
     * Run the database seeds.
     * @return void
    public function run()
            'name'          =>  'Root',
            'description'   =>  'This is the root category, don\'t delete this one',
            'parent_id'     =>  null,
            'menu'          =>  0,

        factory('App\Models\Category', 10)->create();

Now we will update our factory class. Open the CategoryFactory class and update with the below code.

use App\Models\Category;
use Faker\Generator as Faker;

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name'          =>  $faker->name,
        'description'   =>  $faker->realText(100),
        'parent_id'     =>  1,
        'menu'          =>  1,

Last thing, open the DatabaseSeeder class and add the blow in the run() method.


After making all the changes, now we need to update our Category model class.

Adding Mutator for Category Model

Open the Category model class and add the below mutator for our name field.

public function setNameAttribute($value)
    $this->attributes['name'] = $value;
    $this->attributes['slug'] = str_slug($value);

Above mutator will save the slug field automatically whenever we save or create a category in our application.

Adding Parent Child Relationship for Categories

Next we will add couple of relationship defination in our Category model class.

The first relation will be to get the parent category of a category. For that, we will use the belongsTo to define the parent relationship.

public function parent()
    return $this->belongsTo(Category::class, 'parent_id');

Now we will add the hasMany relationship for our category to return the children for our given category.

public function children()
    return $this->hasMany(Category::class, 'parent_id');

Learn More

You can learn more about how to define the one to many relationship in Laravel by reading Introducing One To Many Relationship in Laravel post.


That’s it for now, in the next post we will start creating the categories admin area from where we will manage all our categories.

Code Repository

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

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

12 comments on “Laravel E-Commerce Application Development – Categories Section Part 1

  1. hey Lara shout, my question is related to one of my ecommerce project, issue is that I wants to show checkout details on admin dashboard, Add to Cart Work Perfectly . When user get checkout he/she can fill a form, now I wants all checkout products along a form detail on admin dashboard. Kindly guide me, am beginner

    1. There are different approaches for that, if you are storing the cart data in the database then each cart entry should be assigned to a user_id as the user has to login to start using the cart. Then in your admin, you can load all cart data. If you want to store the checkout details, you can store them in a different table, but you have to make sure your application complies with the GDPR act because you are storing customers personal information.


      1. Thanks #LaraShout, I Hope In Future Lessons You Will Also Add Functionality like that or better then that. If You Don’t Mind Can You Please Add an Extra Lesson of Sub Category .

  2. Illuminate \ Database \ QueryException (2002)
    SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. (SQL: select column_name as `column_name` from information_schema.columns where table_schema = ecommerce and table_name = settings)
    Previous exceptions
    SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. (2002)
    Why this letter ??

  3. Hello, in this e-commerce application, you have different categories of products which have the same type of attribute such as color, size, therefore you are storing attribute in a different table and their values in another table in database, but I have total 12 to 13 categories and each category have different attributes, so cant make a single table of all the attributes, therefore I am thinking to make 2 tables, one for storing categories with id and category name, and then 12 tables for storing products of each category and store the attribute in the same table. I will do the manual entry of products from admin panel so will make forms for submitting the products and select the attribute value from there
    Can you give me a brief idea about implementing this thing and is there any other better way to organize database structure? How can I modify your tutorial according to my project?

  4. Hi, You didn’t Define slug in CategoryTableSeeder class its showing error not define a default value what can i do. ?

  5. The root category is not being added when I seed. I got an empty table. No errors in console. I got success message. Any idea why that might be?

    1. James make sure you have added the categories seeder class to DatabaseSeeder class like below.


      Any problem do let us know.


  6. Everything has been going well until this section

    first error
    The use statement with non-compound name ‘Config’ has no effect

Leave a Reply

Your email address will not be published.


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.

Your little help will keep this site alive and help us to produce quality content for you.