`does not write information to the database` - php

does not save to database
help me understand my mistake
Controller
public function store(Request $request)
{
$item = Cart::where('product_id', $request->product_id);
if ($item->count()) {
$item->increment('quantity');
$item = $item->first();
} else {
$item = Cart::forceCreate([
'product_id' => $request->product_id,
'quantity' => 1,
]);
}
return response()->json([
'quantity' => $item->quantity,
'product' => $item->product
]);
}
Store
addProductToCart (product, quantity) {
axios.post('http://127.0.0.1:8000/api/cart', {
product_id: product.id,
quantity
})
},
when clicking on the addItems(for instance) button, the items are not added to the database

my mutation happened to be in the wrong module
add_to_cart(state, {product, quantity}) {
let productInCart = state.cart.find(item => {
return item.product.id === product.id;
});
if (productInCart) {
productInCart.quantity += quantity;
return;
}
state.cart.push({
product,
quantity
})
},

Related

Add to each array element another element php

I'm having one more problem in the logical realm.
I have an array containing ids:
$product_ids = ['1', '5', '3']; <- Example
Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".
$finalarray = ["1,3", "5,2", "3,10"];
Next I indicate the code that is executed in the controller (where is what I previously told):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).
Another option I thought of is passing objects to an array:
[{id: 1, quantity: 3}]
But I don't know how to get to create that object, I'm still kind of new hehe.
I hope I have explained myself well, English is not my native language. I'm sorry.
I am attentive to your comments !! Greetings.
PS: I am using Laravel
To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.
I am considering one is Order class.
<?php
class Order {
private $id;
private $quantity;
public function setId(int $id) {
$this->id = $id;
return $this;
}
public function getId(){
return $this->id;
}
public function setQuantity(int $quantity) {
$this->quantity = $quantity;
return $this;
}
public function getQuantity(){
return $this-> quantity;
}
public function toArray(){
return [
'id' => $this->getId(),
'quantity' => $this->getQuantity()
];
}
}
?>
another is OrderList.
<?php
class OrderList {
private $orderList;
public function __construct(Order ...$orders) {
$this->orderList = $orders;
}
public function toArray(){
$arr = [];
foreach ($this->orderList as $order) {
$arr[] = $order->toArray();
}
return $arr;
}
}
?>
and then use like
$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));
//Output
string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
You do not need json_encode, I have added it to print only.
Nevermind, resolved ->
$prodsfinal = array();
for ($i = 0; $i < sizeof($cantidades); $i++) {
$array = [
'id' => json_decode($input['productos'][$i]),
'cantidad' => (int) $cantidades[$i],
];
array_push($prodsfinal, $array);
}

PHP-LARAVEL 6 Created category returns 404

I need your help please.
When I create a new category at my laravel project it doesn't show the products I inserted after, but returns "404 page not found" and 2 other categories I created in phpmyadmin at the start of the project (for tests) they are working good. I can't find the problem why it returns 404 doesnt matter with or without products in it.
Thank you!!! Heres the code:
---------------------------------------------ROUTES:------------------------------------------
#CMS
Route::prefix('cms')->group(function () {
Route::middleware(['cmsguard'])->group(function () {
Route::get('dashboard', 'CMSController#dashboard');
Route::get('orders', 'CMSController#orders');
Route::resource('menu', 'MenuController');
Route::resource('content', 'ContentController');
Route::resource('categories', 'CategoriesController');
Route::resource('products', 'ProductsController');
});
});
--------------------------------------------CREATE CATEGORY:------------------------------
$category = new self();
$category->ctitle = $request['title'];
$category->carticle = $request['article'];
$category->curl = $request['url'];
$category->cimage = $image_name;
$category->save();
Session::flash('sm', 'Category Is Saved!');
--------------------------------------UPDATE CATEGORY:----------------------------------------
$category = self::find($id);
$category->ctitle = $request['title'];
$category->carticle = $request['article'];
$category->curl = $request['url'];
if ($image_name) {
$category->cimage = $image_name;
}
$category->save();
Session::flash('sm', 'Category Is Updated!');
------------------------------------------CATEGORIE REQUEST:----------------------------------
class CategorieRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules(Request $request)
{
$item_id = !empty($request['item_id']) ? ',' . $request['item_id'] : '';
return [
'title' => 'required',
'url' => 'required|regex:/^[a-z\d-]+$/|unique:categories,curl' . $item_id,
'article' => 'required',
'image' => 'image'
];
}
}

Unique data input to Laravel session

To create a shopping cart, I would like to add the same product only once to my Laravel session. I have tried this condition within my controller, but it's still not working. Any ideas?
Controller
$sessions = Session::get('items.item');
foreach ($sessions as $session) {
if ($request->name == $session['name']) {
return;
} else {
Session::push('items.item', [
'name' => $request->name,
]);
}
}
Your code will add the item immediately if the first item it finds does not have the same name. You have to check all items before adding the new one.
$sessions = Session::get('items.item');
$inItems = false;
foreach ($sessions as $session) {
if ($request->name == $session['name']) {
$inItems = true;
break;
}
}
if (!$inItems) {
Session::push('items.item',[
'name' => $request->name,
]);
}

Update pivot table in Laravel 5.4 [duplicate]

This question already has answers here:
getting the value of an extra pivot table column laravel
(3 answers)
Closed 4 years ago.
I have two models: Event and Ticket. I assigned between them Many-To-Many relationship: Here it is:
Ticket model:
public function events()
{
return $this->belongsToMany('App\Event');
}
Event model:
public function tickets()
{
return $this->belongsToMany('App\Ticket');
}
And then I in my Controller I want to update pivot table data:
public function register(Request $request)
{
$event = Event::findOrFail($request->event);
if(count($event) > 0) {
foreach($request->tickets_type as $key => $value) {
if($value !== null) {
for($i = 0; $i < (int) $value; $i++) {
$sale = new Sale;
$sale->event_id = $request->event;
$sale->event_type = $request->event_type;
$sale->user_id = Auth::user()->id;
$sale->ticket_type = $key;
$sale->save();
$sale->qr = $this->generateQR($sale->event_id, $sale->ticket_type, $sale->id);
$sale->update();
}
$event->tickets->pivot->ticket_quantity -= $value;
}
}
return response()->json([
'success' => true,
'message' => 'Покупка билетов успешно завершена.',
'data' => $request->all()
], 200);
} else {
return response()->json([
'success' => false,
'error' => 'Попытка подмены данных.'
], 403);
}
}
On $event->tickets->pivot->ticket_quantity -= $value; it throws me an error:
Property [pivot] does not exist on this collection instance.
What's the workaround?
change this
$event->tickets->pivot->ticket_quantity -= $value;
to this
$vent->tickets()->attach(id, ['ticket_quantity' => $value]);
You can also use sync which deletes the extra entries which are not in your input
$vent->tickets()->sync(id, ['ticket_quantity' => $value]);
Hope this helps

laravel pivot table unique

order_id....product_id....product_quantity....created_at....updated_at
this is my pivot table...In my OrderRequest table I want to assign product_id as unique. But when I write like this;
public function rules()
{
return [
'product_id' => 'unique:order_product,product_id'
];
}
I encounter a problem. product_id becomes unique. but not only in an order, it becomes totally unique. I want to use this product_id in other orders but I can't. what can I do? How can I assign product_id as unique for each order_id values?
In your controller assuming that you call saveProducts method so :
function saveProducts($request){
validateProductList($request->input('product_list'))
$order->product()
->updateExistingPivot($product_id[$i],
array(
'product_quantity' => $product_quantity[$i],
'product_status' => $product_status[$i],
'updated_at' => Carbon::now() ));
// ....
}
function validateProductList($productIds){
if(isProductIdDuplicated($productIds)){
$error = 'You have a duplicated product in your Order, please edit it'
return redirectBack()-withError();
}
}
function isProductIdDuplicated($productIds){
$occureces_array = productIds();
foreach($productIds as $id){
if(++$occureces_array[$id] > 1){
return true;
}
}
return false;
}
And in your view you have access to this $error variable.
Thank you for your help. I have ended up the issue and it works now...
this is a part of my view;
<div class="grid1">
{!! Form::label('product_list'.$product_row, Lang::get('home.Select Product')) !!}
</div>
<div class="grid2 searchDrop">
{!! Form::select('product_list[]', $product_list, null, ['style'=>'width:150px;'])!!}
and this is part of my controller;
public function store(OrderRequest $request)
{
$order = Order::create( $request->all());
$product_list= $request->input('product_list');
$product_quantity = $request->input('product_quantity');
$product_status = $request->input('product_status' );
/* attach pivot table */
$order->product()->attach($product_list);
/* get the product list as array */
foreach($product_list as $key => $product_id)
{
$order->product()->updateExistingPivot($product_id, array(
'product_quantity' => $product_quantity[$key], // product_quantity is array
'product_status' => $product_status[$key], // product_status is array
'updated_at' => Carbon::now()
));
}
flash(Lang::get('home.The order has been created!'));
return redirect(url('/admin/orders/details',$order->id))->with('flash_message');
}
this is my OrderRequest;
public function rules()
{
return [
'customer_id' => 'required',
'product_quantity.*' =>'not_in:0',
'product_list' => 'product_unique', //custom validation in AppServiceProvider
];
}
and this is my AppServiceProvider;
public function boot()
{
Validator::extend('product_unique', function($attribute, $value, $parameters, $validator) {
if ( count(array_unique($value))!=count($value) ) {
return false;
}
return true;
});
}
Finally, in my validation.php I added;
"product_unique" => "Please select a product only once!",

Categories