Laravel : Doesn't have a default value - KeyProduct with Faker - php

I can't add a keyproduct when i'm creating a new product.
I get the error SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`activation_key`, `updated_at`, `created_at`) values (57394cd3-54f8-3e95-a951-e11f029fa0f5, 2020-05-27 17:09:08, 2020-05-27 17:09:08))
I don't know why, it asks me that.
What I tried :
category_id is my first column that i'm adding in my table. If I put ->nullable() to category_id , I get the same error with name that is the next column in my table.
This is imy code :
ProductController
public function store(Request $request)
{
$inputs = $request->except('_token');
$quantity = $inputs['quantity'];
factory(KeyProduct::class, $quantity)->create();
foreach ($inputs as $key => $value) {
$home->$key = $value;
}
$home->image=$path;
$home->save();
return redirect('admin/gamelist');
}
Product_table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->string('image')->nullable();
$table->string('activation_key')->nullable();
$table->timestamps();
});
KeyProduct_table.php
Schema::create('key_products', function (Blueprint $table) {
$table->increments('id');
$table->string('activation_key');
$table->timestamps();
});
Keyproduct.php
public function products()
{
return $this->HasOne('App\Product')->withPivot('quantity');
}
Product.php
class Product extends Model
{
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function keyProduct()
{
return $this->HasOne('App\KeyProduct');
}
protected $fillable = ['quantity'];
}
KeyProductFactory.php
use App\KeyProduct;
use App\Product;
$factory->define(KeyProduct::class, function (Faker $faker) {
$product = factory(Product::class)->create();
return [
'activation_key' => $product->activation_key,
];
});
ProductFactory.php
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'activation_key' => $faker->uuid
];
});
CategoryFactory
use App\Category;
use Faker\Generator as Faker;
$factory->define(Category::class, function (Faker $faker) {
return [
'activation_key' => $faker->uuid
];
});
Thanks for your help.

It fails because the product is created without you setting that category_id or name at the time of creation. Make them nullable() or change your creation method accordingly.

In your SQL you provided values for "activation_key", "updated_at" and "created_at" columns only, so other fields must satisfy at least one statement:
have an AUTO_INCREMENT option;
have a DEFAULT value;
allow NULL values.
You haven't provided enough data to complete the query.

Add more $fillables to your Product.php Model. By looking at your migrations it should look like this:
protected $fillable = [
'category_id', 'name', 'image', 'activation_key', 'quantity'
];

Related

Laravel table update issue General error: 1364 Field 'start_date' doesn't have a default value

hope you are safe and doing well. I am facing an issue with laravel relational table. I have three table, USER, CLIENT ,ORDER and CAR_PARKING. Now Client is related to user and ORDER is related to both Client and USER while CAR_PARKING related to ORDER only. What i am facing like issue is that when I am trying to update table ORDER it says #General error: 1364 Field 'start_date' doesn't have a default value#
Below are my different table models and controller
public function updateOrderCarParking(Request $request, $id)
{
if (Auth::check()) {
$carParkingData = $request->only('removed', 'removed_date');
$validateCarParking = Validator::make($carParkingData, [
'removed' => 'required|boolean',
'removed_date' => 'nullable'
]);
if ($validateCarParking->fails()) {
return response()->json($validateCarParking->errors(), 422);
}
$orderData = $request->only('paid', 'amount_paid', 'overdue', 'currency', 'user_id');
$validateOrder = Validator::make($orderData, [
'amount_paid' => 'required|regex:/^\d*+(\.\d{1,2})?$/',
'currency' => [
'required',
Rule::in(['USD', 'CAD'])
],
"paid" => "required|boolean",
'overdue' => 'regex:/^\d*+(\.\d{1,2})?$/'
]);
if ($validateOrder->fails()) {
return response()->json($validateOrder->errors(), 422);
}
$updateCarParking = CarParking::updateOrCreate([
'removed' => $request->removed,
'removed_date' => $request->removed_date,
]);
$order = Order::find($id);
$order->carParkings()->save($updateCarParking);
$updateOrder = Order::find($id);
$updateOrder->amount_paid = $request->amount_paid;
$updateOrder->paid = $request->paid;
$updateOrder->currency = $request->currency;
$updateOrder->overdue = $request->overdue;
$updateOrder->user_id = Auth::user()->id;
$updateOrder->save();
if ($order && $updateOrder) {
return response()->json([
'success' => true,
'message' => 'Order updated successfully',
'data' => $order
], Response::HTTP_OK);
}
} else {
return response()->json([
'success' => false,
'message' => 'Can not update',
], Response::HTTP_UNAUTHORIZED);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $fillable = ['order_type', 'amount_paid','client_id', 'user_id', 'price', 'currency', 'paid', 'overdue'];
public function user()
{
return $this->belongsTo(User::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
public function carParkings(){
return $this->hasMany(CarScrap::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CarParking extends Model
{
use HasFactory;
protected $fillable = ['start_date', 'end_of_free_charge', 'order_id', 'removed', 'removed_date'];
public function order()
{
return $this->belongsTo(Order::class);
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->decimal('price', 8, 2);
// $table->date('start_date');
$table->enum('order_type', ['Storage rent', 'Forklift', 'Ramp', 'Car Parking', 'Car Scrap', 'Shipping']);
$table->enum('currency', ['USD', 'CAD']);
$table->boolean('paid')->default('0');
$table->decimal('amount_paid')->default(0);
$table->decimal('overdue')->nullable();
$table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->timestamps();
});
Schema::enableForeignKeyConstraints();
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('orders', function (Blueprint $table) {
$table->dropConstrainedForeignId("client_id");
$table->dropConstrainedForeignId("user_id");
});
Schema::dropIfExists('orders');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarParkingsTable extends Migration
{
public function up()
{
Schema::create('car_parkings', function (Blueprint $table) {
$table->id();
$table->date('start_date');
$table->date('end_of_free_charge');
$table->boolean('removed')->default("0");
$table->date('removed_date')->nullable();
$table->timestamps();
$table->foreignId('order_id')->constrained('orders')->onDelete('cascade');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::table('car_parkings', function (Blueprint $table) {
$table->dropConstrainedForeignId("order_id");
});
Schema::dropIfExists('car_parkings');
}
}
What am I doing wrong?
Replace your existing method with this:
class CreateCarParkingsTable extends Migration
{
public function up()
{
Schema::create('car_parkings', function (Blueprint $table) {
$table->id();
$table->date('start_date')->nullable();
$table->date('end_of_free_charge');
$table->boolean('removed')->default("0");
$table->date('removed_date')->nullable();
$table->timestamps();
$table->foreignId('order_id')->constrained('orders')->onDelete('cascade');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::table('car_parkings', function (Blueprint $table) {
$table->dropConstrainedForeignId("order_id");
});
Schema::dropIfExists('car_parkings');
}
}
If you get error for any other field then make it nullable as I had done in start_date
Set start_date to Nullable in Database Migration.
Example:
$table->date('start_date')->nullable();
How can we imagine that only two lines of code have solved the errors. No need of setting nullable on any column. I got the solution by doing this code below:
$client = Client::findOrFail($client->id);
$client->update($request->all());
But i put in the model the relationships function. I meant in the CLIENT model i put
public function orders(){
return $this->hasMany(Order::class);
}
same thing for order model

My database isn't accepting 'name' property

I am trying to pass in "name" in my "friends" through my controller.
I have already made a "names" table with names in it
I keep getting "Trying to get property 'name' of non-object" This error.
Here's my FriendsController:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Friend;
use Illuminate\Support\Facades\Auth;
use App\Name;
class FriendsController extends Controller
{
public function store(Request $request)
{
$name = Name::all()->random(1)[0]->name;
Friend::create([
'my_id'=>Auth::user()->id,
'friends_id'=>$request->friends_id,
'name' => $name->name,
]);
Friend::create([
'friends_id'=>Auth::user()->id,
'my_id'=>$request->friends_id,
'name' => $name->name,
]);
return redirect('/home');
}
}
Here's my friends table:-
public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->id();
$table->string('my_id');
$table->string('friends_id');
$table->string('name')->nullable();
$table->timestamps();
});
}
Here's My Names table:-
public function up()
{
Schema::create('names', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Can anyone please help me?
'name' => $name should be correct as Tim mentioned. If it wasn't saved into your database, it was probably because name column is guarded in your model.
Try adding protected $guarded=['id']; or protected $fillable=['name'];in your Friend Model and see if that works. To know more about this, You can check laravel's Mass Assignment. Cheers :)
Here's The Solution:-
public function store(Request $request)
{
$name = Name::inRandomOrder()->first()->name;
Friend::create([
'my_id'=>Auth::user()->id,
'friends_id'=>$request->friends_id,
'name' => $name,
]);
Friend::create([
'friends_id'=>Auth::user()->id,
'my_id'=>$request->friends_id,
'name' => $name,
]);
return redirect('/home');
}
}

How to add table that has foreign key value referring to another table in laravel?

Model 1:
namespace App;
use Illuminate\Database\Eloquent\Model;
class productDescription extends Model
{
protected $table="ProductDescription";
protected $connection="mysql";
public function productPricing()
{
return $this->belongsTo(priceInfo::class);
}
public function salesPackage()
{
return $this->hasMany(packageModel::class);
}
}
Model2:
class packageModel extends Model
{
//
protected $table="subSalesPackage";
protected $connection="mysql";
public function product_description(){
return $this->belongsTo(productDescription::class);
}
}
Controller:
public function addProductDetails(Request $formdescription,$dataId)
{
$description=new productDescription;
$description->deviceCategoryId=$dataId;
$description->productdescriptionid=$this->getproductDescriptionId();
$description->modelName=$formdescription->input('mname');
$description->batteryType=$formdescription->input('batteryType');
//$description->salesPackage =$formdescription->input('package');
$description->skillSet =$formdescription->input('skillSet');
$description->Colour=$formdescription->input('colour');
$description->Material =$formdescription->input('material');
$description->maxAge=$formdescription->input('maxage');
$description->minAge =$formdescription->input('minage');
//$product->productPricing()-save($priceInfo);
//$product->productDetails()->save($description);
$description->save();
$salesPackage=new packageModel;
$salesPackage->salesPackage=$formdescription->input('package');
**$salesPackage->product_description()->associate($description);**
$salesPackage->save();
//echo("success");
return response()->json([
'modelName' => $formdescription->mname,
'colour' => $formdescription->colour,
'rechargable' => $formdescription->rechargable,
'batteryType' => $formdescription->batteryType
]);
//$description->product()->associate($priceInfo);
}
Migration->productdescription:
public function up()
{
//
Schema::create('ProductDescription', function (Blueprint $table) {
$table->engine='InnoDB';
$table->string('productdescriptionid')->primary();
$table->string('product_id');
$table->string('salesPackage');
$table->timestamps();
$table->index(['productDescriptionId']);
});
}
This is my migration for 1st table(model).It has the primary key as'productdescriptionid'.
Migration->subSalespackage
public function up()
{
//
Schema::create('subSalesPackage', function (Blueprint $table) {
$table->increments('id');
$table->string('product_description_id');
$table->string('salesPackage');
$table->foreign('product_description_id')-
>references('productdescriptionid')->on('ProductDescription');
$table->timestamps();
$table->index(['id']);
});
}
Here I have referred the productdescriptionid as foreign key.And when I add this salespackage table,the values should get added with the value of productdescriptionid(productDescription).
But the error i'm getting is can't able to add or update a child row.
You should try this:
return response()->json([
'SKUID' => $priceInfo->SKUID,
'listingStatus' => $priceInfo->listingStatus,
'MRP' => $priceInfo->MRP,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getproductId()
]);

Simple mutator screwing with SQL Query? - Laravel

I want to be able to set the user_id via the setUserIdAttribute mutator but it won't work. The code works fine when I comment out the mutator. Below is my code and the resulting QueryException error. Please help!
// EventController.php
public function store(Request $request)
{
Event::create([
'name'=>'myName',
'user_id'=>'1'
]);
return 'Success!';
}
// Event.php
class Event extends Model
{
protected $fillable = ['name', 'user_id'];
// It works as expected if I comment this out.
public function setUserIdAttribute($value)
{
// I know this code will run. If i do echo 'foo' it works.
return '1';
}
}
// The migration file
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
// The error I get
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `events` (`name`, `updated_at`, `created_at`) values (myName, 2017-04-23 22:28:31, 2017-04-23 22:28:31))
I think $this->attributes['attribute_name'] is the correct way to mutate.
// Event.php
class Event extends Model
{
protected $fillable = ['name', 'user_id'];
// It works as expected if I comment this out.
public function setUserIdAttribute($value)
{
// Set Attribute's value.
$this->attributes['user_id'] = Auth::id();
}
}

Laravel 5.1 Foreign Key Trouble

I have some trouble getting the foreign key.
My Migrations looks like this (shortened them):
<?php
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('title');
$table->string('filename');
$table->integer('number_of_chapters');
$table->text('input_mpg');
$table->timestamps();
});
}
public function down()
{
Schema::drop('products');
}
}
<?php
class CreateChaptersTable extends Migration
{
public function up()
{
Schema::create('chapters', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->time('input-chapter-start1');
$table->time('input-chapter-end1');
$table->timestamps();
});
Schema::table('chapters', function($table) {
$table->foreign('product_id')->references('id')->on('products');
});
}
public function down()
{
Schema::drop('chapters');
}
}
And my 2 Model like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chapters extends Model
{
protected $table = 'chapters';
protected $fillable = ['input-chapter-start1', 'input-chapter-end1'];
public function product()
{
return $this->belongsTo('App\Product');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public static $rules = [
'email' => 'required|email|max:50',
'title' => 'required|max:50',
'filename' => 'required|max:50',
'input_mpg' => 'required'
];
public function Chapters()
{
return $this->hasMany('App\Chapters');
}
}
And just save it like this in my Controller
$product->save();
$Chapters->save();
And get following error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(generator.chapters, CONSTRAINT chapters_product_id_foreign
FOREIGN KEY (product_id) REFERENCES products (id)) (SQL: insert
into chapters (input-chapter-start1, input-chapter-end1,
updated_at, created_at) values (12:12:12, 12:12:12, 2016-04-25
11:41:31, 2016-04-25 11:41:31))
EDIT
Controller looks like this:
namespace App\Http\Controllers;
class ProductController extends Controller
{
protected $request;
public function request(Request $request)
{
$this->request = $request;
}
public function createProduct(Request $request)
{
$product = new Product;
$Chapters = new Chapters($request->all());
$data = $request->all();
$projectEmail = $request->input('email');
$projectTitle = $request->input('title');
$projectFile = $request->input('filename');
$projectChapters = $request->input('number_of_chapters');
$validator = Validator::make($request->all(), Product::$rules);
if($validator->fails())
{
return Redirect::back()->withInput()->withErrors($validator);
}
$product->fill($data);
if($product->save())
{
$Chapters->product()->associate($product);
$Chapters->save();
return redirect()->route('root')->with('message', 'success')->withInput();
}
else
{
return redirect()->route('newProduct')->with('message', 'Error')->withInput();
}
}
}
Edit I tried Samsquanch suggestion:
And added this in my controller:
$product->save();
$Chapters->product()->associate($product);
$Chapters->save();
but still get this error message:
BadMethodCallException in Builder.php line 2093: Call to undefined
method Illuminate\Database\Query\Builder::products()
The problem is that you're not telling Laravel or MySQL what the foreign key should be.
You have two options here (both from the documentation: https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models)
The first option would be to save chapters through product:
$chapters = $product->chapters()->saveMany($Chapters); // or just->save() if it's only one
The second (and how I generally do it) would be to use associate() which relies on the belongsTo relationship in your Chapters model:
$product->save();
$Chapters->product()->associate($product);
$Chapters->save();
There's also a third, but not recommended, option of just setting the foreign key yourself manually.
Edit:
$product->chapters()->associate($Chapters);
$product->save();

Categories