Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MuhammadUmar's avatar

SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value

I'm new to Laravel and trying to add Product under Category but when I add Product then it shows this error:

SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into products ..."

Initially i was adding these products without under any category than it was working and now its not adding under Category.

can anyone would prefer to provide me its solution?

here is my form:

  <form enctype="multipart/form-data" class="form-horizontal" method="post" action="{{ 
  url('admin/add-product') }}" name="add_product" id="add_product" 
  novalidate="novalidate">{{ csrf_field() }}
      <div class="control-group">
        <label class="control-label">Under Category</label>
        <div class="controls">
          <select name="category_id" id="category_id" style="width:220px;">
            <?php echo $categories_drop_down; ?>
          </select>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label">Product Name</label>
        <div class="controls">
          <input type="text" name="product_name" id="product_name">
        </div>
      </div>
 <div class="uploader" id="uniform-undefined"><input name="image" id="image" type="file" 
 size="19" style="opacity: 0;"><span class="filename">No file selected</span><span 
 class="action">Choose File</span></div>
 div class="form-actions">
        <input type="submit" value="Add Product" class="btn btn-success">
      </div>
    </form>

here is ProductsController:

   public function addProduct(Request $request)
   {
    if ($request->isMethod('post'))
    {
    $data = $request->all();

    $product = new Product;
    $product->product_name = $data['product_name'];
    $product->product_code = $data['product_code'];
    $product->product_color = $data['product_color'];
    if ( ! empty($data['description']))
    {
        $product->description = $data['description'];
    }
    else
    {
        $product->description = '';
    }
    $product->price = $data['price'];

    // Upload Image
    if ($request->hasFile('image'))
    {
        $image_tmp = Input::file('image');
        if ($image_tmp->isValid())
        {
            $extension = $image_tmp->getClientOriginalExtension();
            $filename = rand(111, 99999) . '.' . $extension;
            $large_image_path = 'images/backend_images/products/large/' . $filename;
            $medium_image_path = 'images/backend_images/products/medium/' . $filename;
            $small_image_path = 'images/backend_images/products/small/' . $filename;
            // Resize Images
            Image::make($image_tmp)->save($large_image_path);
            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
            // Store image name in products table
            $product->image = $filename;
        }
    }

    $product->save();

    /*return redirect()->back()->with('flash_message_success','Product has been added 
    successfully!');*/

    return redirect('/admin/view-products')->with('flash_message_success', 'Product has been 
    added successfully!');
    }

   $categories = Category::where(['parent_id' => 0])->get();
   $categories_drop_down = "<option value='' selected disabled>Select</option>";

   foreach ($categories as $cat)
   {
    $categories_drop_down .= "<option value='" . $cat->id . "'>" . $cat->name . "</option>";
    $sub_categories = Category::where(['parent_id' => $cat->id])->get();
    foreach ($sub_categories as $sub_cat)
    {
        $categories_drop_down .= "<option value='" . $sub_cat->id . "'>&nbsp;&nbsp;--&nbsp;" . 
       $sub_cat->name . "</option>";
      }
   }

   return view('admin.products.add_product')->with(compact('categories_drop_down'));
  }
0 likes
34 replies
Equalizee's avatar

I think it has something to do with the fillable in your Product model.

Try to add this in your Product.php:

protected $fillable = [
    'category_id'
]
3 likes
Vilfago's avatar

You don't inform about the category_id when you fill your model.

 if ($request->isMethod('post'))
    {
    $data = $request->all();

    $product = new Product;
    $product->product_name = $data['product_name'];
    $product->product_code = $data['product_code'];
    $product->product_color = $data['product_color'];
    $product->category_id = $data['category_id']; // <<< NEW LINE

You should maybe take a look at validation : https://laravel.com/docs/5.7/validation

And you can set a method for GET method, and another one for POST method in your route file, and thus don't need to check if ($request->isMethod('post')) at the top of your controller.

signar's avatar

@developer_ You're not providing a category_id. You're missing $product->category_id = $data['category_id']; in your controller

signar's avatar

@developer_ Have you made sure that $data['category_id'] gets passed through to your controller? Does your $categories_drop_down output the options with a value correctly? At least try dd($data['category_id']);. If that's empty, then check the HTML

MuhammadUmar's avatar

@SIGNAR - yes $data['category_id'] gets passed through controller, and $categories_drop_down is only showing the category id in output not the text formatted value like other values

Vilfago's avatar
   public function addProduct(Request $request)
   {
    if ($request->isMethod('post'))
    {
    $data = $request->all();

    $product = new Product;
    $product->product_name = $data['product_name'];
    $product->product_code = $data['product_code'];
    $product->product_color = $data['product_color'];
    $product->category_id = $data['category_id']; // <<< NEW LINE
    if ( ! empty($data['description']))
    {
        $product->description = $data['description'];
    }
    else
    {
        $product->description = '';
    }
    $product->price = $data['price'];

    // Upload Image
    if ($request->hasFile('image'))
    {
        $image_tmp = Input::file('image');
        if ($image_tmp->isValid())
        {
            $extension = $image_tmp->getClientOriginalExtension();
            $filename = rand(111, 99999) . '.' . $extension;
            $large_image_path = 'images/backend_images/products/large/' . $filename;
            $medium_image_path = 'images/backend_images/products/medium/' . $filename;
            $small_image_path = 'images/backend_images/products/small/' . $filename;
            // Resize Images
            Image::make($image_tmp)->save($large_image_path);
            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
            // Store image name in products table
            $product->image = $filename;
        }
    }

    dd($request->all(), $product); // <<< NEW LINE
    $product->save();

//[...]

What did you get ?

signar's avatar

@developer_ I see the error which is the same as the title of this thread. You're still not setting the category_id value for the product when creating a product. You need to fix that by $product->category_id = $data['category_id']

signar's avatar

@developer_ Good! Then the category_id is passed through. You only need to set it on your product :) $product->category_id = $data['category_id'];

MuhammadUmar's avatar

@SIGNAR - bro i hv added this line and also clear the view using php artisan view:clear by i dont know y getting the same error

Vilfago's avatar

@signar no, the dd was before saving to db... but everything seems clear and correct.

You can maybe check in the Product if you have the category_id attribute, and if yes... I don't understand the error you get...

Can we see your "Product" Model ?

MuhammadUmar's avatar

@SIGNAR - but its not saving in db and m not getting the added product in browser, its still showing the same error, now i hv cleard the histroy of browser but still same issue

signar's avatar

@vilfago You're right. And I don't understand the error eighter. There must be a spelling error or something like that..

MuhammadUmar's avatar

product model :

  public function product(){
    return $this->hasMany('App\Product','product_id');
  }
Vilfago's avatar

The App\Product file, not the method in probably your category model.

But with what you show, you can try

 public function addProduct(Request $request)
   {
    if ($request->isMethod('post'))
    {
    $data = $request->all();
    $category = \App\Category::findOrFail($data['category_id']); //<<< NEW LINE

    $product = new Product;
    $product->product_name = $data['product_name'];
    $product->product_code = $data['product_code'];
    $product->product_color = $data['product_color'];

    if ( ! empty($data['description']))
    {
        $product->description = $data['description'];
    }
    else
    {
        $product->description = '';
    }
    $product->price = $data['price'];

    // Upload Image
    if ($request->hasFile('image'))
    {
        $image_tmp = Input::file('image');
        if ($image_tmp->isValid())
        {
            $extension = $image_tmp->getClientOriginalExtension();
            $filename = rand(111, 99999) . '.' . $extension;
            $large_image_path = 'images/backend_images/products/large/' . $filename;
            $medium_image_path = 'images/backend_images/products/medium/' . $filename;
            $small_image_path = 'images/backend_images/products/small/' . $filename;
            // Resize Images
            Image::make($image_tmp)->save($large_image_path);
            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
            // Store image name in products table
            $product->image = $filename;
        }
    }

 // $product->save(); <<< comment this line
    $category->products()->save($product);

//[...]

It should at least give you a new error.

MuhammadUmar's avatar

@VILFAGO - error:

 Call to undefined method App\Category::products()

is there any issue in model than can u tell me

Vilfago's avatar

oO

So please, put all code of both Product and Category Model.

MuhammadUmar's avatar

@VILFAGO - category model:

 public function categories(){
    return $this->hasMany('App\Category','parent_id');
}

product model:

public function product(){
    return $this->hasMany('App\Product','product_id');
 }
Vilfago's avatar

You have to inverse both method.

Add product (and named it products) to Category, and category (instead of categories) to your product model.

And give us all the text please... it usually begins with

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
 [...]
}
1 like
MuhammadUmar's avatar

@VILFAGO - changed category model:

<?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Category extends Model
  {
    public function category(){
    return $this->hasMany('App\Category','parent_id');
  }
 }

product model:

   <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

   class Product extends Model
   {
     public function products(){
      return $this->hasMany('App\Product','product_id');
    }
  }
Vilfago's avatar
Vilfago
Best Answer
Level 20
<?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Category extends Model
  {
     public function products(){
     return $this->hasMany('App\Product');
  }

}
   <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

   class Product extends Model
   {
    public function category(){
    return $this->belongsTo('App\Category');

    }
  }
 public function addProduct(Request $request)
   {
    if ($request->isMethod('post'))
    {
    $data = $request->all();
    $category = \App\Category::findOrFail($data['category_id']); //<<< NEW LINE

    $product = new Product;
    $product->product_name = $data['product_name'];
    $product->product_code = $data['product_code'];
    $product->product_color = $data['product_color'];

    if ( ! empty($data['description']))
    {
        $product->description = $data['description'];
    }
    else
    {
        $product->description = '';
    }
    $product->price = $data['price'];

    // Upload Image
    if ($request->hasFile('image'))
    {
        $image_tmp = Input::file('image');
        if ($image_tmp->isValid())
        {
            $extension = $image_tmp->getClientOriginalExtension();
            $filename = rand(111, 99999) . '.' . $extension;
            $large_image_path = 'images/backend_images/products/large/' . $filename;
            $medium_image_path = 'images/backend_images/products/medium/' . $filename;
            $small_image_path = 'images/backend_images/products/small/' . $filename;
            // Resize Images
            Image::make($image_tmp)->save($large_image_path);
            Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
            Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
            // Store image name in products table
            $product->image = $filename;
        }
    }

 // $product->save(); <<< comment this line
    $category->products()->save($product);

//[...]
1 like
Next

Please or to participate in this conversation.