Laravel whereIn issue (array expected, int given) error - laravel

public function store(OrderCreateRequest $request)
{
$formField = $request->validated();
$totalAmount = 0;
// get the price of products of product_id using whereIn
$products = DB::table('products')
->select('price')
->whereIn('id', $formField['product_id'])
->get();
foreach ($products as $product) {
$totalAmount += $product->price;
}
$order = Order::create([
'product_id' => $formField['product_id'],
'user_id' => Auth::id(),
'total' => $totalAmount,
'status' => false,
]);
$response = [
'message' => 'order placed',
'created' => new OrderResource($order),
];
return response($response, 201);
}
what is wrong with this piece of code?
error => Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, int given,

You are giving an int to whereIn(), whereIn is a function to check a column value against multiple values.
->whereIn('status', ['pending', 'completed'])
In your case either product_id should be an array, or you should just use a simple where().
->where('id', $formField['product_id'])

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

Sync command wont update values

Hello i have this code in Laravel that updates existing many-to-many relationship tables so when i use the sync command the values update wrong, this is the code:
public function update(Request $request, $id)
{
$order = Order::where('id', $id)->first();
$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($values); //the problem is here
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
If i have 2 values like:
Product1 -> amount: 250
Product2 -> 100
And i updatet these existing values to
Product1 -> amount: 350
Product2 -> 200
The result will be
Product2 -> 200
Product2 -> 200
If i make this line of code dd($order->products()->sync($values)); i get this result
If i add a new product with the existing ones i get this result
From what im understanding the first result is replaced with the second one or removed, why does this happen?
So, you have this code:
public function update(Request $request, $id)
{
$order = Order::where('id', $id)->first();
$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($values); //the problem is here
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}
The issue with it, is that sync is getting wrong IDs, because $values has numeric autoincrementals IDs: 0, 1, 2, etc.
What you need to pass to the sync is either an array of IDs [1, 2, 3], or an array of arrays (when you want to update columns related to that ID, for example: [1 => ['amount' => 100], 2, 3].
Let me try to modify your code to help you.
Let's assume you orders table and products table. You also have a pivot table called order_product table, so you store the relation in there. This order_product table has:
id
order_id
product_id
amount
So, your code should be like this:
public function update(Request $request, $id)
{
$validated = $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 = Order::find($id); // I would change this to use implicit binding
$order->update($validated); // Don't use $request->all(), you are using unvalidated values
foreach ($request->productOrder as $product) {
$values[$product['product_id']] = [
'amount' => $product['amount']
];
$amount = Product::find($product['product_id']);
$totalValue = $product['amount'] + $amount->amount;
$amount->update(['amount' => $totalValue]);
}
$order->products()->sync($values); // Now it will work
$orders = Order::all();
$orders->load('client', 'products');
return view('orders/index', compact('orders'));
}

laravel excel import data does not properly working

I’m working on laravel excel import. The data can be loaded using
$data = Excel::load($path)->get(); command. But, when i try to loop through $data object and put it in $insert[], some fields remaining empty.
my import function look like
public function import(request $request) {
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = [
'Item_name' => $value->Item_name,
'Manufacturer' => $value->Manufacturer,
'Serial_no' => $value->Serial_no,
'Model_no' => $value->Model_no,
'status' => $value->status,
'Price' => $value->Price,
'photo' => $value->photo,
'user_id' => $value->user_id,
'deletedBy' => $value->deletedBy,
'created_at' => $value->created_at,
'updated_at' => $value->updated_at,
];
}
if(!empty($insert)){
$insertData = DB::table('inventories')->insert($insert);
if ($insertData) {
Session::flash('success', 'Your Data has successfully imported');
}else {
Session::flash('error', 'Error inserting the data..');
return redirect()->back();
}
}
}
return redirect()->back();
}
when I dd($data); the result looks as
and the result of dd($insert); looks as
if any friend can help me that why some fields like Item_name, Manufacturer, and Serial_no remain null, would be appreciated.
solved!
all value->item_names must write in lowercase; I thought that it should match with the database table column names.

why my updateOrInsert doesn't work laravel

I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?
foreach($datas as $data){
DB::table('users')->updateOrInsert([
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
}
Check out [updateOrInsert] this documentation (https://laravel.com/api/6.x/Illuminate/Database/Query/Builder.html#method_updateOrInsert). You need two parameters. One is the matching attributes (i.e., the attributes you would use to identify your record in case it exists), the other is your array (the new values you wish to insert or update the record with).
updateOrInsert(array $attributes, array $values = [])
Example
DB::table('users')->updateOrInsert(
[
'user_connect_id' => $user->connect_id
],
[
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
There are two arguments in updateOrInsert method.The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs containing the columns to be updated.
For e.g :
DB::table('users')
->updateOrInsert(
['email' => 'john#example.com', 'name' => 'John'],
['votes' => '2']
);
Check this link for syntax : Laravel Doc
// Inseart code
public function create()
{
return view('admin.category.create');
}
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required'
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Saved','Success');
return redirect()->route('admin.category.index');
}
// Update code
public function edit($id)
{
$category =Category::find($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

Resources