I know it's some dump mistake, but i can't locate it for a while. I have table Meals and table Ingredient with relation many-to-many. Want to input some fake data and create ingredient_meal table. I post some code below but when i go for db:seed --class=MealSeeder i get this error
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into meals
(updated_at, created_at) values (2020-05-29 16:26:55, 2020-05-29 16:26:55))
guessing that this factory isn't working right but can't find solution anywhere, i could pass this issue by putting nullable() in migration and updateing my data but that don't seems me right. Thanks in advance for help!
MealFactory.php
$factory->define(App\Meal::class, function (Faker $faker) {
return [
'title' => $faker->realText($maxNbChars = 10),
'description' => $faker->realText($maxNbChars = 20),
];
});
$factory->define(App\Ingredient::class, function (Faker $faker) {
static $id = 1;
return [
'title' => $faker->realText($faker->numberBetween(10,15)),
'slug' => $id++, //$faker->unique()->numberBetween(1,20),
];
});
Model Meal.php
protected $fillable = ['title','description'];
public function ingredients()
{
return $this->belongsToMany('App\Ingredient');
}
Model Ingredient.php
protected $fillable = ['title'];
public function meals()
{
return $this->belongsToMany('App\Meal');
}
Meal migration
Schema::create('meals', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('status')->default('created');
$table->string('category')->nullable();
$table->timestamps();
//$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
MealSeeder.php
factory(App\Meal::class, 10)->create()->each(function ($meals) {
$meals->ingredients()->save(factory(App\Ingredient::class)->make());
});
factory(App\Ingredient::class, 10)->create()->each(function ($ingredients) {
$ingredients->meals()->save(factory(App\Meal::class)->make());
});
// Get all the ingredients attaching up to 3 random ingredient to each meal
$ingredients = App\Ingredient::all();
// Populate the pivot table
App\Meal::all()->each(function ($meal) use ($ingredients) {
$meal->ingredients()->attach(
$ingredients->random(rand(1, 3))->pluck('id')->toArray()
);
});
EDIT:
I moved on, didn't found right solution. I set in migrations, nullable() propethy for 'title' and 'description' attributes. Run seeder and than fill out all null data trought DB::update. It look so ugly now :(
Related
It's since two days that I'm trying to solve an issue that i face when i try to insert a record in the DB.
I'm building a project where an admin can create a list of places to visit for users.
I have created 3 tables and relative models as follow : places , place_categories, category_places (this the pivot table).
places table has the following inside :
Schema::create('places', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('google_place_id');
$table->unsignedBigInteger('property_id');
$table->foreign('property_id')->references('id')->on('properties');
});
And the Place model has the following :
protected $fillable = [
'google_place_id',
'property_id'
];
public function property(){
return $this->belongsTo(Property::class);
}
public function category(){
return $this->belongsToMany(PlaceCategory::class);
}
The place_categories table has the following code :
Schema::create('place_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
the PlaceCategory model has the following :
protected $fillable = [
'name'
];
public function place(){
return $this->belongsToMany(Place::class);
}
While the pivot category_places table has the following :
Schema::create('category__places', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('place_id');
$table->foreign('place_id')->references('id')->on('places');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('place_categories');
$table->timestamps();
});
And the Category_Place has the following code :
protected $table = 'category_places';
protected $fillable = [
'category_id',
'place_id',
];
}
In my PlaceController, in the store method i wrote the following :
public function store(Request $request)
{
$googlePlaceId = $request->input('google_place_id');
$propertyId= $request->input('property_id');
$categories= $request->input('categories');
$place = Place::create([
'google_place_id' => $googlePlaceId,
'property_id'=> $propertyId,
]);
$place->category()->attach($categories);
return redirect()->route('home', ['property'=> $propertyId])->with('message', 'Place correctly created');
}
Now, when i try to insert a new place with relative categories i keep getting the following error :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myhosthtl.place_place_category' doesn't exist
insert into `place_place_category` (`place_category_id`, `place_id`) values (1, 3)
So he's looking for a table called place_place_category that obviously does not exist, but where do he get this table from? I have also declared the protected $table in my Category_Place model.
After debugging a bit the code, i found out the the error i thrown at line 63 in the store method at this line :
$place->category()->attach($categories);
It seem like he cant find the place_categories table, but he should insert in the category_places the record for the pivot, not in the places_categories.
Is there anybody able to help me? What Am i doing wrong?
Thank you so much for your help.
I'm trying to implement a many-to-many relationship with more than two tables in Laravel.
Migration For Relationship Table
public function up()
{
Schema::create('lab_form_detail', function (Blueprint $table) {
$table->unsignedBigInteger('color_id');
$table->unsignedBigInteger('lab_form_id');
$table->unsignedBigInteger('pontics_design_id');
$table->unsignedBigInteger('teeth_design_id');
$table->integer('quantity');
$table->string('teeth_number');
$table->foreign('lab_form_id')->references('id')->on('lab_forms');
$table->foreign('color_id')->references('id')->on('colors');
$table->foreign('pontics_design_id')->references('id')->on('pontics_designs');
$table->foreign('teeth_design_id')->references('id')->on('teeth_designs');
});
}
Lab Form Model
class LabForm extends Model
{
use HasFactory;
public $timestamps = false;
public function colors()
{
return $this->belongsToMany(Color::class, 'lab_form_detail', 'lab_form_id', 'color_id')
->withPivot([
'pontics_design_id',
'teeth_design_id',
'quantity',
'teeth_number'
]);
}
public function ponticsDesigns()
{
return $this->belongsToMany(PonticsDesign::class, 'lab_form_detail', 'lab_form_id', 'pontics_design_id')
->withPivot([
'color_id',
'teeth_design_id',
'quantity',
'teeth_number'
]);
}
public function teethDesigns()
{
return $this->belongsToMany(TeethDesign::class, 'lab_form_detail', 'lab_form_id', 'teeth_design_id')
->withPivot([
'color_id',
'pontics_design_id',
'quantity',
'teeth_number'
]);
}
}
I also use belongsToMany for other related models.
When I try to insert a new row, I need to use functions for the relationship to insert.
For example:
$lf = LabForm::find(1);
$lf->colors()->attach(1, [
'pontics_design_id' => 2,
'teeth_design_id' => 1,
'quantity' => 10,
'teeth_number' => '30 to 40'
]);
As you can see, when inserting a new row, I need to use one of colors, teethDesigns, ponticsDesigns. Also, I need to insert values differently which depend on the functions that define the relationship.
My question is, can I combine related values into one function and insert them all at the same time? Like:
public function labFormDetail()
{
// insert all values at once
'lab_form_id', 'pontics_design_id', 'color_id', 'teeth_design_id','quantity', 'teeth_number'
}
Or should I create a model for this relationship table?
Or you may suggest your approach for this kind of relationship.
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'
];
please I am new to Laravel, I want to use Laravel API Resource to store database inside database.
I have 3 Tables
Users
Category
Category_User (this is a pivot table)
In my Controller (OnboardsControllers), I have this to store data
public function store(Request $request)
{
$category_user = Category_User::firstOrCreate(
[
'user_id' => $request->user()->id,
'category_id' => $request->$category->id,
],
);
return new CategoryUserResource($category_user);
}
In my CategoryUserResource I have this
public function toArray($request)
{
return [
'user_id' => $this->user_id,
'category_id' => $this->category_id,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
In my Pivot Table, I have this
public function up()
{
Schema::create('category_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
In my model, I added this
protected $fillable = [
'user_id', 'category_id',
];
In my route/api
Route::post('/category_user', 'OnboardsController#onboardupdate');
I believe the error is here
'user_id' => $request->user()->id,
When I removed it, it didn't returned any error
When I tried to save to my database using Postman to test, it not saving. Please, I don't know what I am doing wrong.
Thanks
To be honest, you do not need a model Category_User (but you need a table).
In Laravel a more concise approach is used:
public function store(Request $request)
{
$user = User::find($request->input('user_id'));
$user->categories()->attach($request->input('category_id'));
}
Also I'm not sure if you have declared a method categories() in model User:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
I also strongly doubt the existence of method user() of class Request.
If the request parameter has a name category_id, then you need to access it like this:
$request->input('category_id');
i wonder to know how to insert data into pivot table when using a belongsto many relationship i can read the data from database now but i dont know how to store data in database and in my invoice_product table here is the code
model of invoce :
class Invoice extends Model
{
protected $fillable = ['title','description','client_id','product_id'];
public function user() {
return $this->hasOne('App\Client','id','client_id');
}
public function products()
{
return $this->belongsToMany('App\Product', 'invoice_product', 'invoice_id')
->withPivot('product_quantity')
->as('invoice_products_pivot');
}
}
controller of invoice :
public function store(Request $request)
{
//Validate
$request->validate([
'title' => 'required|min:3',
'description' => 'required',
]);
$invoices = Invoice::create([
'title' => $request->title,
'description' => $request->description,
'client_id' => $request->client_id,
'product_id' => $request->product_id,
]);
return redirect('admin/invoices/' . $invoices->id);
}
this stores an invoice into invoice table but i want to get the client_id and product_id or ids cause it must be multiple products and save them into invoice_product table which migration is down here
public function up()
{
Schema::create('invoice_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('client_id');
$table->integer('product_id');
$table->integer('product_quantity');
$table->timestamps();
});
}
to insert data into intermediate or pivot table for many to many relationshiop
you can use attach eloquent method like below
$invoice->products()->attach($product_id)
$product->invoices()->attach($invoice_id)
but your invoice product migration looks a bit odd it should be like this
public function up()
{
Schema::create('invoice_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_id'); // id of the invoice table
$table->integer('product_id'); // id of the product table
$table->integer('product_quantity'); // client_id should go to the invoice table
$table->timestamps();
});
}