Laravel 5.5 duplicate insert to database on submit - php

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.

Related

Laravel Update Function Don't Save New Data

So I have trouble updating data from edit form. I tried to use 'dd' and it's collect all the data it needs. No error, but the data on database not change.
public function update(Request $request, Stationery $stationery)
{
$validated = $request->validate([
'category_id' => 'required',
'nama' => 'required',
'satuan' => 'nullable',
'harga' => 'required',
'keterangan' => 'nullable'
]);
// dd($validated);
Stationery::where('id', $stationery->id)
->update($validated);
return redirect('/barang/pakaihabis')->with('success', 'Data Berhasil Diubah!!');
}
The success message pop out but the data still same.
The only protected in the model Stationery
protected $guarded = ['id'];
You can use:
$stationery->update($validated);
There is no need for where because you use route model binding ;)

How can I store barcode inside validate request in Laravel

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);

Array to string conversion (laravel 7)

I want to make a quiz app in Laravel and I've got some error: array to string conversion
This is my controller:
public function validateForm1($request)
{
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'options.*' => 'required|string',
'correct_answer' => 'required',
]);
}
public function buat(Request $request)
{
$data = $this->validateForm1($request);
$question = (new Pertanyaan)->storeQuestion($data);
$Answer = (new Jawaban)->storeAnswer($data,$question);
return redirect()->back()->with('message','Pertanyaan berhasil disimpan');
}
This is my question model:
public function storeQuestion($data)
{
return Pertanyaan::create($data);
}
This is my answer model:
public function storeAnswer($data, $question)
{
foreach ($data['options'] as $key => $option) {
$is_correct = false;
if ($key == $data['correct_answer']) {
$is_correct = true;
}
$answer = Jawaban::create([
'question_id' => $question->id,
'answer' => $option,
'is_correct' => $is_correct,
]);
}
}
You have to use like this
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'correct_answer' => 'required',
]);
Then your error remove automatically array to string conversion
this error i got when i use guarded in model, so i change it to fillable and it work properly.
sorry if im not capturing all of my model.
after read the documentation about special variable eloquent, i lil understand.
here the link i read but in indonesian leanguage. and sorry for my bad english sir. im new here
https://id-laravel.com/post/mengenal-eloquent-variable-spesial/
When I had this error, it was caused by an error in my Model. I had the table name formatted as an array, like protected $table = ['log'];. Correcting this to protected $table = 'log'; fixed the problem.

Laravel saving data to two locations

I'm working on a larvel project where the user can create appointments. In addition I've created another model called clients so when a user creates an appointment the users "client" data is saved.
In my appointments controller I have the following: -
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
//create appointment
$apt = new Appointment;
$apt->name = $request->input('name');
$apt->user_id = auth()->user()->id;
$apt->save();
//create client
$client = new Client;
$client->first_name = $request->input('name');
$client->user_id = auth()->user()->id;
$client->save();
return redirect('/appointments')->with('success', 'Appointment created');
}
When saving the data it works and stores the data in the clients table however I know this isn't the cleanest way of saving the data, but what is the "laravel" way of doing this?
There's nothing wrong with your code. It's totally fine keeping it that way.
I prefer to say Model::create() to create models in one statement.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
Appointment::create([
'name' => request('name'),
'user_id' => auth()->id()
]);
Client::create([
'first_name' => request('name'),
'user_id' => auth()->id,
]);
return redirect('/appointments')->with('success', 'Appointment created');
}
You can also use tap() function:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
tap(Appointment::create(['name' => request('name'), 'user_id' => auth()->id()]), function ($newAppoinment) {
Client::create([
'first_name' => $newAppoinment->name,
'user_id' => auth()->id,
]);
});
return redirect('/appointments')->with('success', 'Appointment created');
}
Or the best approach could be using model events:
class Appointment extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($appointment) {
Client::create([
'user_id' => $appoinment->user_id,
'first_name' => $appoinment->name,
])
});
}
}

Input data is not stored as expected in Laravel 6

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);
}

Categories