ErrorException Array to string conversion Laravel - laravel

Here is my code in the controller.
I want multiple data to insert into a database but I have a problem with Array:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
foreach($request->id_product as $item => $value)
$datax = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();

If you want to insert multiple row at a time try this:
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
$datax = [];
foreach($request->id_product as $item => $value)
array_push($datax ,[
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
]);
Tr_detail::insert($datax);
}
return redirect()->back();

You are overwritting your $datax variable, you need to create an array of arrays to pass on to your insert() function:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0) {
$datax = [];
foreach ($request->id_product as $item => $value)
$datax[] = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();
}

Related

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 Create Multiple input with laravel API?

I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.
Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}

Laravel - How to Update Dynamic Input Fields

In my Laravel-8, I have this code:
public function add(Request $request){
if( $request->ajax() ){
$rules = array(
'first_name.*' => 'required',
'country.*' => 'required'
);
$error = Validator::make($request->all(),$rules);
if($error->fails()){
return response()->json([
'error' => $error->errors()->all(),
]);
}
$first_name = $request->first_name;
$country = $request->country;
for( $count = 0; $count < count($first_name); $count++ ){
$data = array(
'first_name' => $first_name[$count],
'country' => $country[$count],
);
$insert_data[] = $data;
}
DynamicField::insert($insert_data);
return response()->json([
'success' => 'Data added Successfully',
]);
}
}
This successfully Inserts record.
How do I do the update to this same code?
I mean public function update ...

Cannot use object of type Gloudemans\Shoppingcart\CartItem as array

I save image in database as array ["product-04.jpg"]. I don't know how to display image to view. I used Crinsane/LaravelShoppingcart and got the following error: "Cannot use object of type Gloudemans\Shoppingcart\CartItem as array". Can everyone help me?
ProductController I saved image in db:
if($request->hasFile('images')){
$files = $request->file('images');
$extension = ['png','jpg','gif','jepg'];
foreach ($files as $key => $item) {
$nameFile = $item->getClientOriginalName();
$exFiles = $item->getClientOriginalExtension();
if(in_array($exFiles, $extension)){
$item->move(public_path().'/upload/images',$nameFile);
$arrNameFile[] = $nameFile;
}
}
}
if($arrNameFile){
$dataInsert = [
'name_product' => $nameProduct,
'categories_id' => json_encode($categories),
'colors_id' => json_encode($colors),
'sizes_id' => json_encode($sizes),
'brands_id' => $brand,
'price' => $price,
'qty' => $qty,
'description' => $description,
'image_product' => json_encode($arrNameFile),
'sale_off' => $sale,
'status' => 1,
'view_product' => 0,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => null
];
if($pd->addDataProduct($dataInsert)){
$request->session()->flash('addPd','success');
return redirect()->route('admin.products');
} else {
$request->session()->flash('addPd','Fail');
return redirect()->route('admin.addProduct');
}
} else {
$request->session()->flash('addPd','Can not upload image');
return redirect()->route('admin.addProduct');
}
}
CartController: I add products and want to show list products in cart
public function addCart(Request $request, $id)
{
$product = Products::select('name_product', 'id', 'price', 'qty', 'image_product')->find($id);
if(!$product) return redirect('/');
Cart::add([
'id' => $id,
'name' => $product->name_product,
'qty' => 1,
'price' => $product->price,
'options' => [
'images' => json_decode($product->image_product, true),
]
]);
return redirect()->back();
}
public function getListCart(){
$products = Cart::content();
return view('frontend.cart.showCart', compact('products'));
}
And view i get image in src : {{ URL::to('/') }}/upload/images/{{ $product->image_product[0] }}

Laravel 5.6 how to delete if there are any records of User

I'm trying to use updateOrCreate in that case but didn't work. So that's why i'm using this. I'll check database before store data. If there are any records of this user I'll delete that record. If there aren't any records I'll create records. Problem is how to delete if there are any records of User.
public function store(Request $request,Choice $choice){
$time = $request->input('time');
$user = Choice::where('user_id','=',Auth::id())->first();
if ($user === null) {
foreach ($request->input('number') as $key => $value) {
Choice::create([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
return redirect()->route('choices.index');
}
else{
$choices = Choice::where('user_id',Auth::id())->orderBy('id')->get()->toArray();
dd($choices);
foreach ($choices as $index) {
$index->delete();
}
foreach ($request->input('number') as $key => $value) {
Choice::create([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
return redirect()->route('choices.index');
}
}
Your function will be look like this,
public function store(Request $request,Choice $choice){
$time = $request->input('time');
$choice = Choice::where('user_id','=',Auth::id())->first();
if ($choice === null) {
foreach ($request->input('number') as $key => $value) {
Choice::create([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
else{
$choices = Choice::where('user_id',Auth::id())->delete();
foreach ($request->input('number') as $key => $value) {
Choice::create([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
return redirect()->route('choices.index');
}
If any confusion feel free to ask and I hope you understand.
You can simply call delete by user id which will make sure if there are any previous record it will be deleted.
public function store(Request $request,Choice $choice){
$time = $request->input('time');
// delete records which belong to user
Choice::where('user_id', Auth::id())->delete();
// add new records
foreach ($request->input('number') as $key => $value) {
Choice::create([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
return redirect()->route('choices.index');
}

Resources