Laravel E-Commerce Application Development – Attributes Section Part 1

Laravel E-Commerce Application Development – Attributes 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 part 10 of the Laravel E-Commerce Application Development series. In this part will add the model, migrations, and seed for attributes 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.

The basic concept of using attributes for our products (which we will cover in the coming posts) will be to attach extra information with our product. For example, a product can have a different size and color. Every color or size can have some extra price, which will be added to the product’s price.

Keeping that in mind, we will need to create two different models, Attribute and AttributeValue. For example, color or size can be stored in attributes table and their values like red, black, blue, small, medium and large can be stored in the attribute_values table.

There are endless possibilities for how we can implement attributes for products in an e-commerce application. I will keep it simple for the sake of this series.

So let’s start implementing this in our application.

Creating Attributes Model and Migration

To save our attributes in database table we will need to create a migration and model. Open your command terminal and run the below command to generate a model and migration for the attribute.

php artisan make:model Models\Attribute -m

The -m flag will create a migration file for our Attribute model. Above command will generate a Attribute model in app/Models folder and a migration file for this model in database/migrations folder.

Open your migration file and update with the below class.

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

class CreateAttributesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attributes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('code')->unique();
            $table->string('name');
            $table->enum('frontend_type', ['select', 'radio', 'text', 'text_area']);
            $table->boolean('is_filterable')->default(0);
            $table->boolean('is_required')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('attributes');
    }
}

In this migration file, we are adding the code column whose value will be unique. The name column which will be displayed on the frontend of the website. An enum column for frontend type which can be a select box, radio button, input box or a text area. Next, we add is_filterable and is_required columns with boolean data type.

Now, open you Attribute model from app/Models folder and update the whole class with the below one.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Attribute
 * @package App\Models
 */
class Attribute extends Model
{
    /**
     * @var string
     */
    protected $table = 'attributes';

    /**
     * @var array
     */
    protected $fillable = [
        'code', 'name', 'frontend_type', 'is_filterable', 'is_required'
    ];

    /**
     * @var array
     */
    protected $casts  = [
        'is_filterable' =>  'boolean',
        'is_required'   =>  'boolean',
    ];
}

In the above model class, we have defined the table for our attributes and fillable property for mass assignment. We also added the $casts property to return our is_filterable and is_required values in boolean format.

Creating Attributes Seed Class

Next, we will add a seeder class for Attribute model. Run the below command to generate a seed class.

php artisan make:seed AttributesTableSeeder

Now open the AttributesTableSeeder class from database/seeds folder and update with the below one.

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

class AttributesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Create a size attribute
        Attribute::create([
            'code'          =>  'size',
            'name'          =>  'Size',
            'frontend_type' =>  'select',
            'is_filterable' =>  1,
            'is_required'   =>  1,
        ]);

        // Create a color attribute
        Attribute::create([
            'code'          =>  'color',
            'name'          =>  'Color',
            'frontend_type' =>  'select',
            'is_filterable' =>  1,
            'is_required'   =>  1,
        ]);
    }
}

Now, open the DatabaseSeeder class from seeds folder and update with the below one.

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(AdminsTableSeeder::class);
        $this->call(SettingsTableSeeder::class);
        $this->call(CategoriesTableSeeder::class);
        $this->call(AttributesTableSeeder::class);
    }
}

Now open your command terminal and run the below commands to migrate the attributes table and add the color and size attributes in it.

php artisan migrate
php artisan db:seed --class=AttributesTableSeeder

If you check your database, you will find a new table named attributes with two rown inserted for size and color.

Creating Attribute Values Model and Migration

In this section, we will create AttributeValue model which will host the values for our attributes. Again open your terminal and run below command.

php artisan make:model Models\AttributeValue -m

Above command will create a migration for attribute_values table in database/migrations folder. Open this migration file and update with the below one.

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

class CreateAttributeValuesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attribute_values', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('attribute_id');
            $table->foreign('attribute_id')->references('id')->on('attributes');
            $table->text('value');
            $table->decimal('price', 2)->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('attribute_values');
    }
}

Using above migration, we are adding a attribute_id column which has a foreign key on attributes table. Next, a value column with text as it’s datatype. You can also use the string. Then a price column which is nullable.

Open the AttributeValue model and replace with the below one.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class AttributeValue
 * @package App\Models
 */
class AttributeValue extends Model
{
    /**
     * @var string
     */
    protected $table = 'attribute_values';

    /**
     * @var array
     */
    protected $fillable = [
        'attribute_id', 'value', 'price'
    ];

    /**
     * @var array
     */
    protected $casts = [
        'attribute_id'  =>  'integer',
    ];
}

Creating Attribute Values Seed Class

In this section, we will create a seed class for our AttributeValue model. Run the below command in terminal to generate a seed class.

php artisan make:seed AttributeValuesTableSeeder

Open this seed class and update it with the below one.

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

class AttributeValuesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $sizes = ['small', 'medium', 'large'];
        $colors = ['black', 'blue', 'red', 'orange'];

        foreach ($sizes as $size)
        {
            AttributeValue::create([
                'attribute_id'      =>  1,
                'value'             =>  $size,
                'price'             =>  null,
            ]);
        }

        foreach ($colors as $color)
        {
            AttributeValue::create([
                'attribute_id'      =>  2,
                'value'             =>  $color,
                'price'             =>  null,
            ]);
        }
    }
}

In this seed class, we are simply adding some sizes and colors in the attribute_values table.

Now, run the below commands.

php artisan migrate
php artisan db:seed --class=AttributeValuesTableSeeder

Adding Relationship to Attributes and Attribute Values

In this section, we will add the relationship between our Attribute and AttributeValue models. Open the Attribute model and add the below function in it.

/**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function values()
    {
        return $this->hasMany(AttributeValue::class);
}

In above code, we are defining a One To Many Relationship using hasMany() method as our attribute will have many values.

Now, in our AttributeValue we will define the inverse of this relationship using the belongsTo method as a value belongs to a attribute.

Open your AttributeValue model and add the below function.

/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function attribute()
    {
        return $this->belongsTo(Attribute::class);
}

Conclusion

That’s it for now, in the next post we will start adding a attributes section in our admin area.

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.

17 comments on “Laravel E-Commerce Application Development – Attributes Section Part 1

  1. Hello, Can I use only one repository with multiple models? I have the same kind of model and migration with different form fields, therefore, I am separating them in different tables, but the method they will use like list product, create, update, delete will be same just the params will be different,
    PLEASE SUGGEST

    1. Yes, you can. All you have to do is create parent constructor in the base repository and instantiate the model classes in it.

  2. While migrating the table it generates the following error? How can I fix sir?
    Migrating: 2019_08_31_133833_create_attribute_values_table

    Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can’t create table `yenesuk`.`#sql-2ebc_13a` (errno: 150 “Foreign key co
    nstraint is incorrectly formed”) (SQL: alter table `attribute_values` add constraint `attribute_values_attribute_id_foreign` foreign key (`attribute_i
    d`) references `attributes` (`id`))

      1. Thank you, sir, I fixed it, the problem was due to forign key and primary key datatype contradiction.
        I chnaged $table->unsignedInteger(‘attribute_id’);
        in to
        $table->bigInteger(‘attribute_id’)->unsigned();

  3. Hi All, in the AttributeValue migration, change
    $table->unsignedInteger(‘attribute_id’);
    to
    $table->unsignedBigInteger(‘attribute_id’);

    if no you will get this erro:
    Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `attribute_values` add constraint `attribute_values_attribute_id_foreign` foreign key (`attribute_id`) references `attributes` (`id`))

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.