I have form with dynamic tables in it where i can add/remove rows, I want to save the data into Transaction_in and Transaction_in_detail table, when i save the data to Transaction_in table is saved as expected but not with Transaction_in_detail.
When I submit the data no matter how many row I put inside the table the saved data inside Transaction_in_detail table always give me 10 all null rows.
Store Controller
public function store(Request $request)
{
$request->validate([
'supplier_id' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_id' => 'required',
'device_brand_id' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
foreach ($transaction_in as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in->id[$tin],
'DeviceType_id' => $transaction_in->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in->device_brand_id[$tin],
'spek_device' => $transaction_in->device_spec[$tin],
'harga_device' => $transaction_in->price[$tin],
'jumlah_device' => $transaction_in->amount[$tin],
'total_harga_device' => $transaction_in->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
The following is the output from dd().
I don't know where the mistake is; this is the model.
Transaction_in Model
class Transaction_in extends Model
{
protected $guarded = [];
public function get_suppliers()
{
return $this->belongsTo(Supplier::class, 'Supplier_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
}
Transaction_in_detail Model
class Transaction_in_detail extends Model
{
protected $guarded = [];
public function get_transction_in_id()
{
return $this->belongsTo(Transaction_in::class, 'Transaction_in_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
}
The Form is inside Transaction_in View and that Store Controller is from transaction_inController, both DeviceType_id and DeviceBrand_id are foreign key.
This is Transaction_in table in database work as expected.
Remove foreach in your function and you can insert data directly to transaction in detail table
public function store(Request $request)
{
...
$transaction_in->save();
for($i=0; $i < count($request->device_brand_id); $i++){
$tdin[] = array(
'Transaction_in_id' => $transaction_in->id,
'DeviceType_id' => $request->device_type_id[$i],
'DeviceBrand_id' => $request->device_brand_id[$i],
'spek_device' => $request->device_spec[$i],
'harga_device' => $request->price[$i],
'jumlah_device' => $request->amount[$i],
'total_harga_device' => $request->total_price[$i]
);
}
Transaction_in_detail::insert($tdin);
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
Your store method is a bit weird, this is what I think you should be doing:
public function store(Request $request)
{
$request->validate([
'supplier_id' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_id' => 'required',
'device_brand_id' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->get('supplier_id');
$transaction_in->tanggal_transaksi = $request->get('transaction_in_date');
$transaction_in->save();
Transaction_in_detail::create([
'Transaction_in_id' => $transaction_in->id,
'DeviceType_id' => $request->get('device_type_id'),
'DeviceBrand_id' => $request->get('device_brand_id'),
'spek_device' => $request->get('device_spec'),
'harga_device' => $request->get('price'),
'jumlah_device' => $request->get('amount'),
'total_harga_device' => $request->get('total_price')
]);
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
I think that all 10 rows became null because of the looping takes the count of the table columns.
your code
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
foreach ( $transaction_in as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in->id[$tin],
'DeviceType_id' => $transaction_in->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in->device_brand_id[$tin],
'spek_device' => $transaction_in->device_spec[$tin],
'harga_device' => $transaction_in->price[$tin],
'jumlah_device' => $transaction_in->amount[$tin],
'total_harga_device' => $transaction_in->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}
My Code
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
$transaction_in1 = new Transaction_in();
foreach ( $transaction_in1 as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in1->id[$tin],
'DeviceType_id' => $transaction_in1->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in1->device_brand_id[$tin],
'spek_device' => $transaction_in1->device_spec[$tin],
'harga_device' => $transaction_in1->price[$tin],
'jumlah_device' => $transaction_in1->amount[$tin],
'total_harga_device' => $transaction_in1->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}
Related
I’m getting this error: Indirect modification of overloaded element of App\Models\ has no effect, change ->get(); to ->first->toArray(); another error Call to a member function toArray() on null
here the code
$penjualan = Penjualan::find(session('id_penjualan'));
$detail = PenjualanDetail::with('produk')->where('id_penjualan', session('id_penjualan'))->get();
$transaction = new Penjualan();
foreach ($detail as $item) {
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
'gross_amount' => $penjualan->bayar,
];
$item_details = [
'id' => $penjualan->id_penjualan,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'first_name' => $request->get('uname'),
'last_name' => '',
'email' => $request->get('email'),
'phone' => $request->get('number'),
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$transaction->snap_token = $snapToken;
$transaction->save();
anyone could help me to fix this?
I have done Midtrans payment before.
The problem you've got with your current code are
you want to store snap_token inside your Penjualan model, but you use new Penjualan()
when multiple items are ordered, your code do not support it cause $item_details is a single array inside foreach loop
So here is an updated code with some notes and recommendations.
$id = session('id_penjualan');
$validated = $request->validate([
'uname' => 'required|string',
// 'lname' => 'nullable|string',
'email' => 'required|string',
'number' => 'required|string',
]);
// use single query to retrieve Penjualan and PenjualanDetail
// for product name, recommend to store it within PenjualanDetail, along with price and base_price
$penjualan = Penjualan::query()
->with('details')
->find($id);
if (!$penjualan) {
// you can redirect your customer to cart or any other page
return redirect('cart')->with('error', 'Can not find Penjualan.');
}
$item_details = [];
foreach ($penjualan->details as $item) {
$item_details[] = [
'id' => $item->id,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
// recommended product's name to be stored within PenjualanDetail
'name' => $item->nama_produk,
];
}
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
// "bayar" must not contain any decimal, use cast Money
'gross_amount' => $penjualan->bayar,
];
// Optional
$customer_details = [
'first_name' => $validated['uname'],
'last_name' => '', // $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
// this is a simple array that will be sent to method getSnapToken()
$transaction = [
'transaction_details' => $transaction_details,
'customer_details' => $customer_details,
'item_details' => $item_details,
];
// this method only accept good old array
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$penjualan->snap_token = $snapToken;
// recommend to store your customer detail here, either multiple fields or single array field storing $customer_details
// $penjualan->first_name = $customer_details['first_name'];
// $penjualan->last_name = $customer_details['last_name'];
// $penjualan->email = $customer_details['email'];
// $penjualan->phone = $customer_details['phone'];
// $penjualan->billing_address = $customer_details['billing_address'];
// $penjualan->shipping_address = $customer_details['shipping_address'];
$penjualan->save();
I commented out some parts that you might not use, where I did used them in the past.
Feel free to adjust them to suite your needs.
public function getSnapToken ()
{
$id = session('id_penjualan');
$member = Member::orderBy('nama')->get();
$penjualan = Penjualan::with(['penjualan_detail' => $detail = function ($query) {
$query->where('item', 'kode_produk, subtotal, jumlah, nama_produk');
}])->where('id_penjualan', ('id_penjualan'))
->orderBy('id_penjualan')
->get();
$transaction = array($penjualan);
foreach ( $detail as $item ) {
$transaction_details = [
'order_id' => $this->penjualan->id_penjualan,
'gross_amount' => $this->penjualan->bayar,
];
$item_details = [
'id' => $item->produk->kode_produk,
'price' => $item->jumlah * $item->subtotal,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'id' => $penjualan->member->kode_member,
'first_name' => $validated['uname'],
'last_name' => $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snap_token = '';
try {
$snap_token = \Midtrans\Snap::getSnapToken($transaction);
}
catch (\Exception $e) {
echo $e->getMessage();
}
echo "snap_token = ".$snap_token;
}
public function payment(Penjualan $penjualan)
{
$snap_token = $penjualan->snap_token;
if (is_null($snap_token)) {
$midtrans = new CreateSnapTokenService($penjualan);
$snap_token = $midtrans->getSnapToken();
$snap_token = Penjualan::where('id_penjualan')->update(['snap_token' => $snap_token]);
}
return view('penjualan.payment', ['snap_token'=>$snap_token]);
}
Please I have an issue with my code. whenever I want to update my post it always says my files are empty although I have an old file. Please can you help me to fix it? Thanks in advance.
This my controller
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if (!empty([
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request),
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request),
]));
$data['cover_image'] = $image_path;
$data['cover_music'] = $music_path;
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}
This is the code handly the file
public static function saveFromRequest($file , $path , Request $request)
{
$file_name = Str::slug($request->name, '-').".".$file->extension();
$file->move(public_path($path) , $file_name);
return $path."/".$file_name;
}
I have changed your file condition now try I hope it work for you now.
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if ($request->file('cover_image')) {
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request);
$data['cover_image'] = $image_path;
}
if ($request->file('cover_music')) {
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request);
$data['cover_music'] = $music_path;
}
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}
I have a code on the store function where I save product details. However, the barcode always return empty. I don't know how to save it with Product::create($data);'. Can I ask some direction?
$data = new Product;
$data->name = $request->name;
Do I need to save one by one on an object such as the one above?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use Picqer;
class ProductsController extends Controller
{
public function index() {
$products = Product::orderBy('id')->get();
return view('products.index', compact('products'));
}
public function show(Product $product) {
return view('products.show', ['product' => $product]);
}
public function create() {
$products = Product::all();
return view('products.create', compact('products'));
}
public function edit(Product $product) {
return view('products.edit', compact('product'));
}
public function update(Request $request, Product $product) {
$request->validate([
'code' => 'required',
'barcode' => 'required',
'name' => 'required',
'description' => 'required|string|max:250',
'unit' => 'required|int',
'cost' => 'required',
'srp' => 'required',
'supplier' => 'required|string|max:250',
'quantity_left' => 'required',
'category' => 'required|string|max:250',
'delivered_date' => 'required|date',
'expiration_date' => 'required|date'
]);
$product->code = $request->code;
$product->barcode = $request->barcode;
$product->name = $request->name;
$product->description = $request->description;
$product->unit = $request->unit;
$product->cost = $request->cost;
$product->srp = $request->srp;
$product->supplier = $request->supplier;
$product->quantity_left = $request->quantity_left;
$product->category = $request->category;
$product->delivered_date = $request->delivered_date;
$product->expiration_date = $request->expiration_date;
$product->save();
return redirect()->route('products.index');
}
public function store(Request $request) {
$code = $request->code;
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
$barcode = $generator->getBarcode($code, $generator::TYPE_CODE_128);
$data = $request->validate([
'code' => 'required',
'barcode' => 'max:15|nullable',
'name' => 'required',
'description' => 'required|string|max:250',
'unit' => 'required|int',
'cost' => 'required',
'srp' => 'required',
'supplier' => 'required|string|max:250',
'quantity_left' => 'required',
'category' => 'required|string|max:250',
'delivered_date' => 'required|date',
'expiration_date' => 'required|date'
]);
Product::create($data);
return redirect()->route('products.index')->with('success', 'Product has been added!');
}
public function destroy(Product $product) {
$product->delete();
return back();
}
}
I think I just missed something. I've used this framework: https://github.com/picqer/php-barcode-generator
You need to overwrite the barcode coming from request with the one you generated.
$product = new Product();
$product->name = 'some name';
...
$product->barcode = $barcode;
$product->save();
I made this work by merging the two arrays:
$data = array_merge($data, ['barcode' => $barcode]);
Product::create($data);
I've created a new form for existing users.
And i'm trying to insert the new values into the database, but the values wont save.
public function editUser(Request $request, $id, $check)
{
$curID = $id;
$userData = $request->input();
$curUser = User::Where('id', $curID)->first();
$address = Address::where('id', $userData['address_id']);
------Not working----------------
if(empty($curUser->$address)){
$curUser->insert($address)([
'address_id' => $address->id,
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode']
]);
-------Not working----------------
} else{
$address->update([
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode'],
]);
return redirect('client')->with($this->messageBag, "User edited!");
}
public function editUser(Request $request, $id, $check)
{
$user = User::where('id',$id)->first();
$address = Address::where('id',$request->input('address_id'))->first();
if(empty($address)){
$address=new Address();
}
$address=$this->saveData($address,$request()->all());
$user->update(['address_id'=>$address->id]);
return redirect('client')->with($this->messageBag, "User edited!");
}
protected function saveData(Address $address,array $userData){
$address->region_id= $userData['region'];
$address->country_id= $userData['country'];
$address->city_id= $userData['city'];
$address->street_name= $userData['street_name'];
$address->house_number= $userData['house_number'];
$address->postcode= $userData['postcode'];
$address->save();
return $address;
}
can someone help me...my laravel code insert twice to database when I click submit, it store double data to database,
here is my code :
controller
public function store(Request $request)
{
$this ->validate($request,[
'nim' => 'required|max:8',
'nama' => 'required|max:30',
'alamat' => 'required|max:100',
'jenis_kelamin' => 'required|max:9',
'no_tlp' => 'required|regex:/[0-9]{12}/',
'tempat' => 'required',
'tanggal' => 'required',
'id_jurusan' => 'required'
]);
$simpan = new Mahasiswa([
'nim' => $request->get('nim'),
'nama' => $request->get('nama'),
'alamat' => $request->get('alamat'),
'jenis_kelamin' => $request->get('jenis_kelamin'),
'no_tlp' => $request->get('no_tlp'),
'tempat' => $request->get('tempat'),
'tanggal' => $request->get('tanggal'),
'id_jurusan' => $request->get('id_jurusan')
]);
$simpan->save();
if (Mahasiswa::create($request->all())) {
$request->session()->flash('status', 'success');
$request->session()->flash('pesan', 'Data Berhasil Disimpan');
}else{
$request->session()->flash('status', 'danger');
$request->session()->flash('pesan', 'Data gagal Disimpan!!');
}
return redirect('/Mahasiswa/create');
}
and this my model code :
class Mahasiswa extends Model
{
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','tempat','tanggal','id_jurusan'];
protected $table = 'mahasiswa';
}
Thanks in advance
You are saving your data twice:
$simpan->save();
and then again:
Mahasiswa::create($request->all())
Just remove the $simpan->save(); line.