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
Related
I have a submit and update function for my form and in that form, the user can choose to add an additional row of inputs. These inputs will be saved in a new row, basically, one user can have several rows in the database. I have a problem with the update function, where if the user originally has two rows answered, in the update function if they still fill in two rows, both of the rows in the database will be updated, however, only the first row is getting updated. I tried accessing the key for the arrays and updating based on the array keys but it doesn't work.
Here is my whole controller:
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Facades\Validator;
use App\Http\Livewire\Field;
use Illuminate\Http\Request;
use App\Helpers\Constant;
use App\Models\User;
use App\Models\Application;
use App\Models\Model1;
use App\Models\Model2;
use App\Models\Model3;
use App\Models\Model4;
use Livewire\Component;
use DB;
class ModelComponent extends Component
{
public $i = 1;
public $updateMode = false;
public $model2Rows = [];
public $model4Rows = [];
public $showDiv1 = false;
public $showDiv2 = false;
public $showDiv3 = false;
public $showDiv4 = false;
public $m1_field;
public $m1_field2;
public $m2_field;
public $m2_field2;
public $m3_field;
public $m3_field2;
public $m4_field;
public $m4_field2;
public function openDiv($divNum)
{
if($divNum == 1) {
$this->showDiv1 =! $this->showDiv1;
} else if($divNum == 2) {
$this->showDiv2 =! $this->showDiv2;
} else if($divNum == 3) {
$this->showDiv3 =! $this->showDiv3;
} else if($divNum == 4) {
$this->showDiv4 =! $this->showDiv4;
}
}
public function addMoreModel2Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model2Rows , $i);
}
public function addMoreModel4Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model4Rows , $i);
}
public function removeModel2Rows($i)
{
unset($this->model2Rows[$i]);
}
public function removeModel4Rows($i)
{
unset($this->model4Rows[$i]);
}
public function submit()
{
$user = auth()->user();
$application = Application::create([
'app_type_id' => 1,
'approval_status_id' => 1
]);
$application->users()->save($user);
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
Model1::create([
'user_id' => $user->user_id,
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
Model2::create([
'user_id' => $user->user_id,
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::create([
'user_id' => $user->user_id,
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
$user->save();
alert('success','Your details are saved.');
return redirect()->route('website.landing');
}
public function update()
{
// get user info in session
$user = auth()->user();
$i = 0;
$model2 = Model2::where('user_id', $user->user_id)->get();
$model4 = Model4::where('user_id', $user->user_id)->get();
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
EmploymentDetail::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
$partTime[$key]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
if(!empty($model4[$i])){
$model4[$i]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
} else {
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
}
alert('success','Your income are updated.');
return redirect()->route('borrower.joint_declaration');
}
public function render()
{
$income_informations = DB::table('income_informations')->get();
$showDiv1 = $this->showDiv1;
$showDiv2 = $this->showDiv2;
$showDiv3 = $this->showDiv3;
$showDiv4 = $this->showDiv4;
return view('livewire.model-component',
[
'income_informations' => $income_informations,
'showDiv1'=>$showDiv1,
'showDiv2'=>$showDiv2,
'showDiv3'=>$showDiv3,
'showDiv4'=>$showDiv4,
]);
}
}
I created a variable to store the arrays because I realized that if I simply use the model name and then do updateOrCreate() it will probably only update the first one. But the result of that update function is that it updates the first row in the database, then creates a new row for the additional row, but I want it to update the other rows in the database instead.
For more context, I followed through this tutorial for the adding input fields and saving function. Now I have trouble trying to do the update function.
I'm in dire need of your assistance. I'm following a Laravel 8 Ecommerce tutorial and Im at the checkout stage.
After following all the steps and reconfirming the code a couple of times I get the error subject every time while the tutorial proceeds to success and its driving me nuts!! Pls someone help me understand where I'm going wrong. Thank you. Below is the code. All solutions will be appreciated.
Livewire relationship models
Order Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $table = "orders";
public function user()
{
return $this->belongsTo(User::class);
}
public function orderItems()
{
return $this->hasMany(OrderItem::class);
}
public function shipping()
{
return $this->hasOne(Shipping::class);
}
public function transaction()
{
return $this->hasOne(Transaction::class);
}
}
OrderItem
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OrderItem extends Model
{
use HasFactory;
protected $table = "order_items";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Shipping Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Shipping extends Model
{
use HasFactory;
protected $table = "shippings";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Transaction Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
use HasFactory;
protected $table = "transactions";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Checkout Component
<?php
namespace App\Http\Livewire;
use Cart;
use App\Models\Order;
use Livewire\Component;
use App\Models\Shipping;
use App\Models\OrderItem;
use App\Models\Transaction;
use Illuminate\Support\Facades\Auth;
class CheckoutComponent extends Component
{
public $ship_to_different;
public $firstname;
public $lastname;
public $mobile;
public $email;
public $line1;
public $line2;
public $city;
public $address;
public $country;
public $zipcode;
public $s_firstname;
public $s_lastname;
public $s_mobile;
public $s_email;
public $s_line1;
public $s_line2;
public $s_city;
public $s_address;
public $s_country;
public $s_zipcode;
public $paymentmode;
public $thankyou;
public function updated($fields)
{
$this->validateOnly($fields, [
'firstname' => 'required',
'lastname' => 'required',
'mobile' => 'required|numeric',
'email' => 'required|email',
'line1' => 'required',
'city' => 'required',
'address' => 'required',
'country' => 'required',
'zipcode' => 'required'
]);
if ($this->ship_to_different) {
$this->validateOnly($fields, [
's_firstname' => 'required',
's_lastname' => 'required',
's_mobile' => 'required|numeric',
's_email' => 'required|email',
's_line1' => 'required',
's_city' => 'required',
's_address' => 'required',
's_country' => 'required',
's_zipcode' => 'required',
]);
}
}
public function placeOrder()
{
$this->validate([
'firstname' => 'required',
'lastname' => 'required',
'mobile' => 'required|numeric',
'email' => 'required|email',
'line1' => 'required',
'city' => 'required',
'address' => 'required',
'country' => 'required',
'zipcode' => 'required'
]);
$order = new Order();
$order->user_id = Auth::user()->id;
$order->subtotal = session()->get('checkout', ['subtotal']);
$order->discount = session()->get('checkout', ['discount']);
$order->tax = session()->get('checkout', ['tax']);
$order->total = session()->get('checkout', ['total']);
$order->firstname = $this->firstname;
$order->lastname = $this->lastname;
$order->mobile = $this->mobile;
$order->email = $this->email;
$order->line1 = $this->line1;
$order->line2 = $this->line2;
$order->city = $this->city;
$order->address = $this->address;
$order->country = $this->country;
$order->zipcode = $this->zipcode;
$order->status = 'ordered';
$order->is_shipping_different = $this->ship_to_different ? 1 : 0;
$order->save();
foreach ((Cart::instance('cart'))->content() as $item) {
$orderItem = new OrderItem();
$orderItem->product_id = $item->id;
$orderItem->order_id = $order->id;
$orderItem->price = $item->price;
$orderItem->quantity = $item->qty;
$orderItem->save();
}
if ($this->ship_to_different) {
$this->validate([
's_firstname' => 'required',
's_lastname' => 'required',
's_mobile' => 'required|numeric',
's_email' => 'required|email',
's_line1' => 'required',
's_city' => 'required',
's_address' => 'required',
's_country' => 'required',
's_zipcode' => 'required'
]);
$shipping = new Shipping();
$shipping->order_id = $order->id;
$shipping->firstname = $this->s_firstname;
$shipping->lastname = $this->s_lastname;
$shipping->mobile = $this->s_mobile;
$shipping->email = $this->email;
$shipping->line1 = $this->s_line1;
$shipping->line2 = $this->s_line2;
$shipping->city = $this->s_city;
$shipping->address = $this->s_address;
$shipping->country = $this->s_country;
$shipping->zipcode = $this->s_zipcode;
$shipping->save();
}
if ($this->paymentmode == 'cod') {
$transaction = new Transaction();
$transaction->user_id = Auth::user()->id;
$transaction->order_id = $order->id;
$transaction->mode = 'cod';
$transaction->status = 'pending';
$transaction->save();
}
$this->thankyou = 1;
Cart::instance('cart')->destroy();
session()->forget('checkout');
}
public function verifyForCheckout()
{
if (!Auth::check()) {
return redirect()->route('login');
} else if ($this->thankyou) {
return redirect()->route('thankyou');
} else if (!session()->get('checkout')) {
return redirect()->route('product.cart');
}
}
public function render()
{
$this->verifyForCheckout();
return view('livewire.checkout-component')->layout('layouts.base');
}
}
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();
}
}
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.
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]
]);
}