Laravel updateOrCreate And Increment Value - php

In my app, i'm saving customer interests depending on viewing products, adding to carts, orders and category viewing.
Now here is my customerInterestController
$customerInterest = [
'user_id' => Auth::user()->id,
'interest' => $category_id,
];
$data = [
'cart_interest' => ($column == 'cart') ? 1 : 0,
'order_interest' => ($column == 'order') ? 1 : 0,
'category_interest' => ($column == 'category') ? 1 : 0,
'view_interest' => ($column == 'view') ? 1 : 0,
];
try{
(new CustomerInterest)->insertCustomerInterest($customerInterest, $data);
}catch(Exception $e){
dd($e);
}
And here is my customerInterest Model
public function insertCustomerInterest($customerInterest = [], $data = []){
return $this->updateOrCreate($customerInterest, $data);
}
There is no problem with inserting database. It works.
My Table
id
user_id
interest
cart_interest
order_interest
category_interest
view_interest
user_id and interest columns are composite unique index.
If user_id, interest columns exists
i want to update data
if not i want to insert data.
I use updateOrCreate method but couldn't increase the values in $data array.
How can i do that ?

I solved my problem.
I removed $data array
Here is my code for insert or update
(new customerInterestController)->insertCustomerInterest('category', $category->id);
Here is my model
public function insertCustomerInterest($customerInterest = [], $column){
return $this->updateOrCreate($customerInterest)->increment($column.'_interest');
}

Related

My query will not update, but when i refresh in dd it will

When I run the query normally it won't update the status_order from 0 to 1, but when I put a dd() function after the query to check if it will update properly, it will give the same result the first time I run the code, but when I refresh the page it will update to a 1.
Here's how my code usually looks:
public function payment(Request $request){
$total = 0;
$orderInfo = $this->getOrderInfo();
$json2 = array();
foreach($this->getOrderInfo()->products as $product){
$total += ($product->price * $product->pivot->order_quantity);
}
if(Customer::find(Auth::user()->id)->balance >= $total && $orderInfo !== null){
if($orderInfo->order_status !== 1){
$orderInfo->where('customer_id', Auth::user()->id)
->where('order_status', 0)
->update(['order_status' => 1]);
}
foreach($orderInfo->products as $product){
$json = array('order_id' => $product->pivot->order_id,
'product_id' => $product->pivot->product_id,
'product_name' => $product->name,
'price' => $product->price,
'quantity' => $product->pivot->order_quantity);
array_push($json2, $json);
}
Customer::where('id', Auth::user()->id)->decrement('balance', $total);
array_push($json2, array('order_status' => $orderInfo->order_status));
$productInfo = json_encode($json2, JSON_PRETTY_PRINT);
OrderHistory::create([
'customer_id' => Auth::user()->id,
'orderInfo' => $productInfo
]);
$orderInfo->products()
->detach();
$orderInfo->delete();
return back();
}else{
return "Not enough balance";
}
}
}
Here's where I put my dd() function:
if($orderInfo->order_status !== 1){
$orderInfo->where('customer_id', Auth::user()->id)
->where('order_status', 0)
->update(['order_status' => 1]);
dd($orderInfo->where('customer_id', Auth::user()->id)->where('order_status', 0));
}
The if($orderInfo->order_status !== 1) is put in there for me to check if the query would get skipped at all. I have tried to alter the order in which the code is presented, but it didn't make any difference.
this code produce mass update but doesn't affect your $orderInfo model which is loaded when it had order_status == 0
$orderInfo = $this->getOrderInfo();
// ...
$orderInfo->where('customer_id', Auth::user()->id)
->where('order_status', 0)
->update(['order_status' => 1]);
// in database data was updated, but $orderInfo is already in memory, so
// $orderInfo->order_status == 0
in case you want to get immediately impact on $orderInfo try
// if you order can have only one info
$orderInfo->order_status = 1;
$orderInfo->save();
// if order can have multiple info models
$orderInfo->newQuery()->where('customer_id', Auth::user()->id)
->where('order_status', 0)
->update(['order_status' => 1]);
$orderInfo = $orderInfo->fresh();
docs about fresh() method
as a sidenote here you're doing duplicate getOrderInfo() call
$orderInfo = $this->getOrderInfo();
$json2 = array();
//foreach($this->getOrderInfo()->products as $product) {
foreach($orderInfo->products as $product) {
$total += ($product->price * $product->pivot->order_quantity);
}
update to clarify about comment to main post
truth to be told, i'm confused that this code runs at all. i meant
$orderInfo is an object given you checked its property order_status
but then you call where() on it as if it is a collection (or model).
also its not laravel-query-builder but laravel-eloquent or just
eloquent given you have detach() there.. – Bagus Tesa
if we dig into Illuminate\Database\Eloquent\Model class there is 'magic' method __call
/**
* Handle dynamic method calls into the model.
*
* #param string $method
* #param array $parameters
* #return mixed
*/
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
if ($resolver = (static::$relationResolvers[get_class($this)][$method] ?? null)) {
return $resolver($this);
}
// that's why OP code works
return $this->forwardCallTo($this->newQuery(), $method, $parameters);
}
as you can see if model has no method to call it forwards call to Builder object (result of $this->newQuery()) which is equivalent to ModelName::query()
tbh, i agree that calling eloquent from loaded model is a bit frustrating, but it is 'by design'
In order to do a mass update, what this theoretically is, you need to define all the attributes that you want to mass update in the $fillable array in your Model. (OrderInfo in this case)

Pass id from first model into a Eloquent

I have a problem wanting to pass the id of Products in the subqueries.
The first code is what I have so far. The second is the way I want to do with Eloquent, but I can't.
$result = [];
Product::with(['locals.presentations'])->each(function ($product) use (&$result) {
$body['id'] = $product->id;
$body['nombre'] = $product->nombre;
$sedes = [];
$product->locals->each(function ($local) use (&$sedes, $product) {
$presentations = [];
$local->presentations->each(function ($presentation) use (&$presentations, $local, $product) {
if ($presentation->local_id == $local->id && $presentation->product_id == $product->id) {
$presentations[] = [
'local_id' => $presentation->local_id,
'product_id' => $presentation->product_id,
'presentacion' => $presentation->presentation,
'precio_default' => $presentation->price
];
}
});
...
});
return $result;
I want transform the previous code into this with Eloquent, but I can't pass the product_id into the subqueries:
$products = Product::with(['locals' => function ($locals) {
//How to get the id from Product to pass in the $presentations query ??????
$locals->select('locals.id', 'descripcion')
->with(['presentations' => function ($presentations) {
$presentations
// ->where('presentations.product_id', $product_id?????)
->select(
'presentations.local_id',
'presentations.product_id',
'presentations.id',
'presentation',
'price'
);
}]);
}])->select('products.id', 'nombre')->get();
return $products;
Product
public function locals()
{
return $this->belongsToMany(Local::class)->using(LocalProduct::class)
->withPivot(['id', 'is_active'])
->withTimestamps();
}
Local
public function presentations()
{
return $this->hasManyThrough(
Presentation::class,
LocalProduct::class,
'local_id',
'local_product_id'
);
}
You can simply use the has() method if you have set the relations correctly on the Product and Local models. This will return ONLY the products which has locals AND presentations.
If you want every product but only the locals and presentations with the product_id equals to the products.id, then you don't have to do anything. The relationship you set in your models already checks if the id matches.
$products = Product::has('locals.presentations')
->with(['locals' => function ($locals) {
$locals
->select('locals.id', 'descripcion')
->with(['presentations' => function ($presentations) {
$presentations->select(
'presentations.local_id',
'presentations.product_id',
'presentations.id',
'presentation',
'price'
);
}]);
}])->select('products.id', 'nombre')->get();

Insert a new record if not exist and update if exist, laravel 5.4

Is there any way to insert a new record if doesn't exist and update the record if exist? the following is the code i using.
public function store(Request $request)
{
$inputs = $request->all();
$this->validate($request,[
'course_code'=>'required'
]);
$batch = $request->batch;
$students = User::select('student_id')->where('batch', $batch)->get();
$course_codes = $inputs['course_code'];
$data=[];
foreach ($students as $student) {
foreach ($course_codes as $course_code) {
$data[]=[
'batch' => $batch,
'student_id' => $student->student_id,
'semester' => $inputs['semester'],
'course_code' => $course_code,
"created_at" => \Carbon\Carbon::now(), # \Datetime()
"updated_at" => \Carbon\Carbon::now() # \Datetime()
];
}
}
DB::table('assign_batches')->insert($data);
return redirect('/admin/assign/batch/create')->with('message', 'A batch has been assigned to courses successfully!');
}
Here is my output when I inserted same records again.
But I want one Student Id may have many Course Code but can not be duplicate. So I want to check if student has same course or courses then skip or update it and insert new records.
Please help me.
Thanks.
Check id if exist then update otherwise insert
if(isset($request->id)){
DB::table('assign_batches')->where("id", $request->id)->update($data);
}else {
DB::table('assign_batches')->insert($data);
}
Use firstOrCreate / firstOrNew
$students = User::firstOrNew(['student_id' => $request->student_id, 'course_code' => $request->course_code]);
$students->foo = $request->foo;
$students->save();
for example if you have a table for every each user to vote once or update his vote;
//give the record to use
$record = request('vote');
//checkif there is a record for user in model
$row = Uservoting::where('user_id',Auth->user()->id)->first;
//if true
if($row!==null){
//update
$row::update(['vote' => $record]);
//if there isn't in model
}else{
//create a new row and insert the value
$new_row = new Uservoting();
$new_row->user_id = Auth->user()->id ;
$new_row->vote = $record ;
$new_row->vote();`
}
hope this work:) {{--if you found any bug just tell me--}}

UpdateExistingPivot method doesn't work

I'm trying to update a value in a pivot table. This is my method :
public function updateStatus(Event $event)
{
$this->authorize('updateStatus', $event);
$newStatus = Input::get('status');
$actualPivot = $event->guests()->where('user_id', Auth::id())->first()->pivot;
$id = $actualPivot['id'];
$status = $actualPivot['status'];
if ($newStatus != $status)
{
dd($event->guests()->updateExistingPivot($id, ['status' => $newStatus]));
}
return back();
}
I've checked with HeidiSQL, the row isn't updated how it should be. I've also tried this solution, but it doesn't update the row, it creates a new one. There is the dd() with this method:
array:3 [▼
"attached" => array:1 [▼
0 => 1
]
"detached" => []
"updated" => []
]
This is my guests() relation defined in the Event model:
public function guests()
{
return $this->belongsToMany('App\User')
->using('App\Invitation')
->withPivot('id', 'status')
->withTimestamps();
}
I don't know why the updateExistingPivot() method doesn't work. I hope you can help.
You must use the guest_id or whatever is the name for your foreign key of App\Invitation instead of your pivot id in order to update the existing record, otherwise you have not a relation for the current event that matches your pivot id.
$id = $actualPivot['guest_id']; // change guest_id for your foreig key name of \App\Invitation
$status = $actualPivot['status'];
if ($newStatus != $status)
{
dd($event->guests()->updateExistingPivot($id, ['status' => $newStatus]));
}

Product Variants Data updated with last record Every time in Laravel 5.3

I'm trying to update my products with dynamic variants. There is no issue in adding or deleting but when I trying to update, every time it updates with the last record on every field.
I'm trying to update dynamic variants where I have inserted...
color - red
shape -square
It's about dynamic form-fields, inserts work properly but when I am trying to update it, it updates the first value with both the filled and the second value with both the field and I won't be able to distinguish the field because of the Blade file returns in form of an array.
When I am trying to update with any value it repeats the last value in both the fields, so the output looks like...
shape-square
shape-square
Controller
<?php
public function updateProducts($id, Request $request)
{
$featured = Input::has('featured') ? true : false;
$product = Product::findOrFail($id);
$product->update(array(
'product_name' => $request->input('product_name'),
'product_qty' => $request->input('product_qty'),
'product_sku' => $request->input('product_sku'),
'price' => $request->input('price'),
'reduced_price' => $request->input('reduced_price'),
'cat_id' => $request->input('cat_id'),
'brand_id' => $request->input('brand_id'),
'featured' => $featured,
'description' => $request->input('description'),
'product_spec' => $request->input('product_spec'),
));
$product->update($request->all());
$variants = VariantsOption::where('products_id', $id)->get();
$test = $request->all();
foreach ($variants as $v) {
$x = $v->id;
foreach ($test['variants_id'] as $key => $attrib) {
$var_name = $test['txt'][$key];
$varid = $attrib;
$variants = new VariantsOption;
$data = array(
'variants_id' => $varid,
'variants_name' => $var_name
);
$variants->where('id', '=', $x)->update($data);
}
}
return redirect('/admin/products/');
}
use following in your class
use Illuminate\Database\Eloquent\ModelNotFoundException;
OR add exception handler within your function
// Will return a ModelNotFoundException if no user with that id
try
{
$product = Product::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
dd(get_class_methods($e)) // lists all available methods for exception object
dd($e)
}
It looks like product with that $id is not found so on update it is adding new product in database.

Categories