how to update array in laravel 5? - 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]
]);
}

Related

How to get from request->value one value at a time inside foreach loop

Hello i have this code in laravel controller and i get an error for a single value:
public function store(Request $request)
{
$values = [];
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
'products' => 'required|exists:products,id',
'amount' => 'required',
]);
$order = Order::create($request->all());
foreach ($request->products as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount,
];
$amount = Product::find($product);
$total_value = $request->amount + $amount->amount; //the error happens here
$amount->update(['amount' => $total_value]);
}
$order->products()->attach($values);
return redirect('/')->with('msg', 'Order Saved successfully!');
}
All the values come except the $request->amount that comes as array and not as a single value in a row. This is the error i get:
Unsupported operand types: array + string
This is the product model:
protected $fillable = [
'name',
'price',
'amount',
];
public function orders()
{
return $this->belongsToMany(Order::class);
}
And this is dd($request->amount);
Assuming that $request->amount is directly related to $request->products with the index then you would either need to combine products and amount before you send the request or iterate over products with the index.
foreach ($request->products as $index => $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount[$index], //Reference via index
];
$amount = Product::find($product);
$total_value = $request->amount[$index] + $amount->amount; //Also here
}
}

How to use sync eloquent method

Hello i am trying to make a code that updates existing values by removing existing ones/add new ones or make changes in the existing values. This is the code i have done so far:
public function update(Request $request, $id)
{
$order = Order::find($id);
$request->validate([
'order_number' => 'required',
'client_id' => 'required',
'description' => 'required',
'productOrder' => 'required',
'productOrder.*.product_id' => 'required|distinct|exists:products,id',
'productOrder.*.amount' => 'required|numeric|min:1',
]);
$order->update($request->all());
foreach ($request->productOrder as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product['product_id'],
'amount' => $product['amount'],
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
// $order->products()->sync([$product['product_id'] => array(
// 'product_id' => $product['product_id'],
// 'amount' => $product['amount'], THIS CODE MAKES ERROR BY DELETING ALL THE VALUES EXCEPT ONE
// )]);
}
$order->products()->detach();
$order->products()->attach($values); //I WANT THE CODE TO DO THIS FUNCTIONS BASICALLY
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
I think you should use this
$values = [];
foreach ($request->productOrder as $product) {
/* This is the sync id && This is the pivot column */
$values[$product['product_id']] = ['amount' => $product['amount']];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
// $values keys must be a product_id and its value must be pivot values
$order->products()->sync($values);

How To Store Foreign Key With Different Tables

I have a problem with my script
This is My Code.
1. DataIndustri Migration
public function up()
{
Schema::create('data_industri', function (Blueprint $table) {
$table->id();
$table->string('nama_perusahaan')->nullable();
$table->string('pemilik_perusahaan')->nullable();
$table->string('kategori_id')->nullable();
$table->string('alamat_perusahaan')->nullable();
$table->string('kecamatan_id')->nullable();
$table->integer('klbi')->nullable();
$table->string('slug')->nullable();
$table->string('gambar')->nullable();
$table->integer('nilai_investasi')->nullable();
$table->integer('jml_tenaga_kerja')->nullable();
$table->timestamps();
});
}
2. DataIndustriModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class DataIndustriModel extends Model
{
use HasFactory;
protected $table = 'data_industri';
protected $fillable = [
'nama_perusahaan',
'pemilik_perusahaan',
'alamat_perusahaan',
'kategori_id',
'kecamatan_id',
'nilai_investasi',
'jml_tenaga_kerja',
'koordinat',
'slug',
'gambar',
];
public function kategoris()
{
return $this->belongsTo(KategoriIndustriModel::class, 'kategori_id', 'id');
}
public function kecamatans()
{
return $this->belongsTo(KecamatanModel::class, 'kecamatan_id', 'id');
}
public function produk_industris()
{
return $this->hasMany(ProdukIndustriModel::class, 'nama_perusahaan_id', 'id' );
}
}
produk_industri migration
public function up()
{
Schema::create('produk_industri', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('nama_perusahaan_id')->nullable();
$table->foreign('nama_perusahaan_id')->references('id')
->on('data_industri');
$table->string('komoditi')->nullable();
$table->integer('kapasitas_komoditi')->nullable();
$table->string('satuan_komoditi')->nullable();
$table->timestamps();
});
}
4. DataProdukIndustriModel
class ProdukIndustriModel extends Model
{
use HasFactory;
protected $fillable = [
'nama_perusahaan_id',
'produk_industri_id',
'komoditi',
'kapasitas_komoditi',
'satuan_komoditi',
];
}
and this is my controller
5. StoreController
public function store(Request $request)
{
$this->validate($request, [
'nama_perusahaan' => 'required',
'pemilik_perusahaan' => 'required',
'alamat' => 'required',
'kecamatan' => 'required',
'kategori' => 'required',
'nilai_investasi' => 'required',
'jml_tenaga_kerja' => 'required',
'koordinat' => 'required',
'klbi' => 'required',
'komoditi' => 'required',
'satuan_komoditi' => 'required',
'kapasitas_komoditi' => 'required',
'gambar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
],[
'nama_perusahaan.required' => 'Nama Perusahaan Mohon Diisi',
'pemilik_perusahaan.required' => 'Pemilik Perusahaan Mohon Diisi',
'alamat.required' => 'Alamat Perusahaan Mohon Diisi',
'kecamatan.required' => 'Kecematan Mohon Dipilih',
'kategori.required' => 'Kategori Perusahaan Mohon Dipilih',
'nilai_investasi.required' => 'Nilai Investasi Mohon Diisi',
'jml_tenaga_kerja.required' => 'Jumlah Tenaga Kerja Mohon Diisi',
'koordinat.required' => 'Lokasi Koordinat Mohon Diisi',
'klbi.required' => 'Kode KLBI Mohon Diisi',
'komoditi.required' => 'Jenis Komoditas Belum Diisi',
'satuan_komoditi.required' => 'Satuan Komoditas Belum Diisi',
'kapasitas_komoditi.required' => 'Kapasitas Komoditas Belum Diisi',
'gambar.required' => 'Ukuran Maksimal Gambar 2MB dan Format JPEG, JPG, PNG, GIF'
]
);
$data1 = $request->all();
$data1['nama_perusahaan'] = $request->nama_perusahaan;
$data1['slug'] = Str::slug($request->nama_perusahaan);
$data1['pemilik_perusahaan'] = $request->pemilik_perusahaan;
$data1['alamat_perusahaan'] = $request->alamat;
$data1['kecamatan_id'] = $request->kecamatan;
$data1['kategori_id'] = $request->kategori;
$data1['nilai_investasi'] = $request->nilai_investasi;
$data1['jml_tenaga_kerja'] = $request->jml_tenaga_kerja;
$data1['koordinat'] = $request->koordinat;
$data1['gambar'] = $request->file('gambar')->store('industri','public');
$data2 = $request->all();
$data2['nama_perusahaan_id'] = {{ ????????? }}
$data2['klbi'] = $request->klbi;
$data2['komoditi'] = $request->komoditi;
$data2['satuan_komoditi'] = $request->satuan_komoditi;
$data2['kapasitas_komoditi'] = $request->kapasitas_komoditi;
DataIndustriModel::create($data1);
ProdukIndustriModel::create($data2);
FacadesAlert::success('Berhasil', 'Data Berhasil Tersimpan');
return redirect()->route('index');
}
My question is, how to store nama_perusahaan_id as foreign key in Tabel produk_industri where the value is from id in tabel data_industri
Thanks in advance ..
i hope someone could help me with my script
maybe you should store DataIndustriModel::create($data1) to a variable and after that you can get the nama_perusahaan_id.
$data1 = $request->all();
$data1["nama_perusahaan"] = $request->nama_perusahaan;
$data1["slug"] = Str::slug($request->nama_perusahaan);
$data1["pemilik_perusahaan"] = $request->pemilik_perusahaan;
$data1["alamat_perusahaan"] = $request->alamat;
$data1["kecamatan_id"] = $request->kecamatan;
$data1["kategori_id"] = $request->kategori;
$data1["nilai_investasi"] = $request->nilai_investasi;
$data1["jml_tenaga_kerja"] = $request->jml_tenaga_kerja;
$data1["koordinat"] = $request->koordinat;
$data1["gambar"] = $request->file("gambar")->store("industri", "public");
$data1 = DataIndustriModel::create($data1);
After that you can get nama_perusahaan_id using $data1->id
$data2 = $request->all();
$data2['nama_perusahaan_id'] = $data1->id;
$data2['klbi'] = $request->klbi;
$data2['komoditi'] = $request->komoditi;
$data2['satuan_komoditi'] = $request->satuan_komoditi;
$data2['kapasitas_komoditi'] = $request->kapasitas_komoditi;
ProdukIndustriModel::create($data2);
You can read the documentation from docs

how to avoid duplicate entry in Laravel

I want to give marks for each student for multiple subjects in different grades (10th,11th,12th) now i pick each student id and I can store marks for each student but i want to avoid duplicate entry for each grade and subjects. example if I give 50 marks in 10th grade for Math subject, again if i want to add marks for Math subject in 10th class, system should not accept and throw a message of duplicate entry.
NOTE: i am using Laravel 7
here it is my MarkController store method:
public function store(Request $request)
{
$this->validate($request, [
'subject_id' => 'integer',
'grade_id' => 'required',
'final_marks' => 'required',
]);
$getMarks = Mark::where('student_id',$request->student_id)->first();
if($getMarks->subject_id != $request->subject_id ){
if($getMarks->grade_id != $request->grade_id){
$marks = new Mark();
$marks->student_id = request('student_id');
$marks->subject_id = $request->subject_id;
$marks->grade_id = $request->grade_id;
$marks->final_marks = $request->final_marks;
//dd('New Marks added');
$marks->save();
}
}else{
dd('duplicate entry');
}
return back()->with('marks-created-message', 'Marks added');
}
and this is my Marks table
public function up()
{
Schema::create('marks', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('student_id');
$table->unsignedInteger('subject_id');
$table->unsignedTinyInteger('grade_id');
$table->double('final_marks',8,2);
$table->timestamps();
});
Schema::table('marks', function(Blueprint $table){
$table->foreign('student_id')->references('id')->on('students');
$table->foreign('subject_id')->references('id')->on('subjects');
$table->foreign('grade_id')->references('id')->on('grades');
});
From the code subject should be the only unique column because you can't assign grade without subject.
So the validation rule should look like:
$this->validate($request, [
'subject_id' => 'integer|unique:marks',
'grade_id' => 'required',
'final_marks' => 'required',
]);
Then if you need a customized message for duplicate entry then your validation should look like
$this->validate($request, [
'subject_id' => 'integer|unique:marks',
'grade_id' => 'required',
'final_marks' => 'required',
],[
'subject_id.unique' => 'Duplicate are not allowed',
]);
You can get more info: Form-request-validation
I solved this by adding this logic in MarkController and it worked:
public function store(Request $request)
{
$this->validate($request, [
'subject_id' => 'integer',
'grade_id' => 'required',
'final_marks' => 'required',
]);
$studentId = $request->student_id;
$subjectId= $request->subject_id;
$gradeId= $request->grade_id;
$sub = 0; // declare variable
$std =0; // declare variable
$grd =0; // declare variable
// Searching Record in DB
$marks = DB::table('marks')->where('student_id', $studentId)->where('subject_id', $subjectId)
->where('grade_id', $gradeId)->get();
//checking if record exist in DB
if($marks) {
foreach ($marks as $mark) {
$sub = $mark->subject_id; // assigning vale to variable
$std = $mark->student_id; // assigning vale to variable
$grd = $mark->grade_id; // assigning vale to variable
}
}
if ($sub == $subjectId and $std == $studentId and $grd == $gradeId){
session()->flash('marks-duplicate-message','Marks already exist.');
// return redirect()->route('marks.store',compact('std'));
return back();
}else{
$marks = Mark::create([
'student_id' => $request->student_id,
'subject_id' => $request->subject_id,
'grade_id' => $request->grade_id,
'final_marks' => $request->final_marks,
]);
session()->flash('marks-created-message','Marks added.');
return back();
}
}

Save Many-To-Many Relationship in Laravel 6

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.

Resources