Save Many-To-Many Relationship in Laravel 6 - laravel

i have two table Product and Order that Many-To-Many to each other. so, i created one other Table Middle of them order_table.
I try to save relationship many-to-many, but i got error unit_price doesnt have a default value.
in Product Model
protected $fillable = [
'name', 'price', 'description', 'status'
];
public function orders()
{
return $this->belongsToMany(\App\Order::class);
}
in Order Model
protected $fillable = [
'description', 'ref_no', 'customer_id', 'description', 'active'
];
public function products()
{
return $this->belongsTo(\App\Product::class);
}
And in Order_Product Schema
Schema::create('order_product', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('order_id');
$table->unsignedBigInteger('product_id');
$table->double('unit_price');
$table->integer('quantity')->default(1);
$table->timestamps();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
In ProductController
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'description' => 'nullable',
]);
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->status = $request->input('status');
$product->description = $request->input('description');
$product->save();
$orders = new \App\Order();
$orders->unit_price = $request->unit_price;
$product->orders()->attach($orders);
return response()->json(['created' => true]);
}
I'll appreciate of all ur help.... Thanks....

Validate the Data to insure it exists.
$data = $this->validate($request, [
'unit_price' => 'required|numeric'
]);
$data['unit_price'];
Use the get method and specify a fallback
$product->orders()->attach($order, [
'unit_price' => $request->get('unit_price', 0)
]);
Fill the pivot using "only" for ease of use once you have it worked out:
$product->orders()->attach(
$order, $request->only(['unit_price'])
);

I got error unit_price doesn't have a default value.
This is a Database issue. Please set a default value for unit_price column.

Related

Attatch multiple values from checkox, with many-to-many relation in Laravel

I am trying to attatch book and warehouses upon creating a new book in my laravel project.
At the moment i have a checkbox for each warehouse, in my view:
#foreach($warehouses as $warehouse)
<input type="checkbox" name="checked[]" value="{{ $warehouse->id }}">
{{ $warehouse->address }}
<br/>
#endforeach
And i have the many to many relations in my book and warehouse models:
Book:
class Book extends Model
{
use HasFactory;
protected $table = 'books';
protected $fillable = [
'ISBN', 'publisher_id', 'author_id', 'year', 'title', 'price',
];
public function warehouses()
{
return $this->belongsToMany(Warehouse::class);
}
Warehouse:
class Warehouse extends Model
{
use HasFactory;
protected $table = 'warehouses';
protected $fillable = [
'name', 'address', 'phone', 'url',
];
public function books()
{
return $this->belongsToMany(Book::class);
}
When submitting the foreach in the form on my book.create view, i try to attach each checked warehouses in the same process as creating the new book:
My Create method:
public function create()
{
$authors = Author::all();
$selectedAuthor = Book::first()->author_id;
$publishers = Publisher::all();
$selectedPublisher = Book::first()->publisher_id;
$warehouses = Warehouse::all();
$selectedWarehouse = Book::first()->warehouse_id;
return view('books.create', compact(['authors', 'publishers', 'warehouses'],
['selectedAuthor', 'selectedPublisher', 'selectedWarehouse']
));
}
And my store method to store the created data:
public function store(Request $request)
{
$request->validate([
'ISBN' => 'required',
'author_id' => 'required',
'publisher_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
Book::create($request->all());
$book = Book::first(); // Book::first(); saves to the first found book (id 1), needs to be fixed to the requested book.
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
return redirect()->route('books.index')
->with('success','Book created successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
The problem is my
$book = Book::first();
saves to the first found book (id 1, even though i might be creating book id 43), needs to be fixed to the requested book that is currently being created.
I have updated my store method by assigning
Book::create($request->all());
To my $book variable which solved the problem, my store method now looks like this:
public function store(Request $request)
{
$request->validate([
'ISBN' => 'required',
'author_id' => 'required',
'publisher_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
$book = Book::create($request->all());
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
return redirect()->route('books.index')
->with('success','Book created successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
And saves the many-to-many relational data upon storing.
Thank you very much for the help Dennis :-)

How do I fill order id when creating orders and orderitems table with 1 form?

How do I fill order id when creating orders and orderitems table with 1 form ?
I make order management system by laravel.
When user submit form of order it will create orders and orderitems table where orderitems table has 1 column named order_id. I do not understand how I fill order_id in orderitems table.
This is my OrderController
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderitem = Orderitem::create([
'order_id' => $request->input('order_id'),
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity'),
]);
return redirect()->route('orders.index');
}
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderitem = Orderitem::create([
'order_id' => $order->id,
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity'),
]);
return redirect()->route('orders.index');
}
First of all create a relationships in both model. In the Order model create a hasMany relation:
public function orderItems()
{
return $this->hasMany(OrderItem::class, 'order_id');
}
Then in OrderItem model create a reverse relation:
public function order()
{
return $this->belongsTo(Order::class, 'order_id', 'id');
}
Then finally in the controller
$order = Order::create([
'user_id' => $request->input('user_id'),
]);
$orderItems = $order->orderItems()->create([
'product_id' => $request->input('product_id'),
'quantity' => $request->input('quantity')
]);

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

I am trying to insert data into database but it says:
SQLSTATE[HY000]: General error: 1364 Field 'category_name' doesn't
have a default value (SQL: insert into categories (updated_at,
created_at) values (2019-07-23 02:34:10, 2019-07-23 02:34:10))
My controller:
public function store(Request $request)
{
//dd($request->all());
$request->validate([
'category_name' => 'required',
'category_description' => 'required',
'category_slug' => 'required',
'category_image' => 'required|image',
]);
$path = $request->file('category_image');
$image = $path->getClientOriginalName();
$path->move(public_path('images/backend_images/category_images'));
$category = Category::create($request->all());
return redirect()->back();
}
My model:
protected $fillable = [
'categry_name', 'categry_description', 'categry_slug', 'categry_image'
];
This is a Database table:
There are spelling mistakes in your model as per your controller.
You have to change your model to
protected $fillable = [
'category_name', 'category_description', 'category_slug', 'category_image'
];
If you use database migration, you have to update all the columns like:
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category_name');
$table->string('category_description');
$table->string('category_slug');
$table->string('category_image');
$table->timestamps();
});
While designing your database, be very precise else use 'nullable' in columns which you are unsure if they are mandatory. Nullable declaration in migration is:
$table->string('category_name')->nullable();
categry_name in your $fillable is misspelt. It's missing an e
According to your controller, your model has spelling mistakes
class categories extends Model {
protected $fillable = ['category_name', 'category_description', 'category_slug', 'category_image'];
//only the field names inside the array can be mass-assign
}
More details: What does “Mass Assignment” mean in Laravel

what could be wrong as there is no error displayed and the code isn't processed: enum in Laravel

Migration
In my migration, I have following passed to the database
$table->enum('product_name', ['chocolate', 'Candy','biscuits', 'Berry']);
$table->string('description');
$table->string('product_no');
$table->timestamps();
in my model I have this below the fillable and a function to select a choice.
protected $fillable =[
'product_no','description'
];
protected $product_name = ['chocolate', 'Candy','biscuits', 'Berry'];
public function getProduct_name()
{
return $this->product_name;
}
The problem is I don't know how to handle this in controller and Postman. It is not displaying any error
public function store(Request $request)
{
$this->validate($request, [
'product_no' => 'nullable|product_no',
'description' => 'required|string',
]);
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->products()->save($product))
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'product could not be added'
], 500);
}
What I intend to achieve is to create a front-end in Angular with a drop down to select the product_name (from the list hard-coded) and description and product_no are fillable. However from Postman, I just entered the values for the three fields i.e. product_name, description and product_no
It seems you forgot to replace method and variable names when you copy the votes code
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->votes()->save($vote))
--------------------^^^^^^^-------^^^^^--
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
That should be
if (auth()->user()->products()->save($product))
Also there is another field (product_name) that you're trying to save but it's not fillable.
protected $fillable =[
'product_no','description', 'product_name'
];
And also, you may want to consider that using same pattern when naming your variables and methods. You can say getProductName or get_product_name instead of getProduct_name.

how to update array in laravel 5?

I am trying to update values from an array.
i can create but if I try to update, it updates only last value.
if I use save() i get an error. I tried everything i could researching. no success.
here is my code.
$products = $request->all();
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
foreach( $name as $key => $n) {
$invoice->products()->update([
'invoice_id' => $invoice->id,
'name' => $name[$key],
'price' => $price[$key],
'qty' => $qty[$key],
'total' => $total[$key]
]);
}
if I use save() i get this error
Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given,
thanks
thanks for your help Mr. pyramid. here is the code:
public function update(Request $request, $id)
{
$invoice = Invoice::findOrFail($id);
$invoice->invoice_no = $request->invoice_no;
$invoice->client = $request->client;
$invoice->title = $request->title;
$invoice->client_address = $request->client_address;
$invoice->invoice_date = $request->invoice_date;
$invoice->due_date = $request->due_date;
$invoice->subtotal = $request->subtotal;
$invoice->grandtotal = $request->grandtotal;
$invoice->save();
$products = $request->all();
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
foreach( $name as $key => $n) {
$invoice->products()->update([
//=> $invoice->id,
'name' => $name[$key],
'price' => $price[$key],
'qty' => $qty[$key],
'total' => $total[$key]
]);
}
Session::flash('success', 'Invoice Updated');
return redirect()->route('invoices');
}
with this exactly code I can create and works fine but if i use to update it won't allow me.
database
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_no');
$table->date('invoice_date');
$table->date('due_date');
$table->string('title');
$table->string('client');
$table->string('client_address');
$table->decimal('subtotal');
$table->decimal('grandtotal');
$table->timestamps();
});
products
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_id')->unsigned();
$table->string('name');
$table->string('qty');
$table->string('price');
$table->string('total');
$table->timestamps();
});
relationship
class Invoice extends Model {
protected $fillable =['client','client_address','title','invoice_no','invoice_date','due_date','discount', 'subtotal','grandtotal'];
public function products(){
return $this->hasMany('App\Product', 'invoice_id');
}
}
class Product extends Model
{
protected $casts = [
'name' => 'array',
'price' => 'array',
'qty' => 'array',
'total' => 'array'
];
protected $fillable = ['invoice_id','price','qty','total','name'];
public function invoice(){
return $this->belongsTo('App\Invoice');
}
}
thanks
I still have some doubts but I found something which I think can help you.
$invoice->products()->update($request->all());
$products = $request->all();
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
foreach( $name as $key => $n) {
$invoice->products()->create([
'invoice_id' => $invoice->id,
'name' => $name[$key],
'price' => $price[$key],
'qty' => $qty[$key],
'total' => $total[$key]
]);
}

Resources