Laravel Api - how to put like and dislike - php

I’m trying to create an API request for like and dislike in my Laravel project:
Route::post('like', ‘Api\ApiController#like’);
The function in the ApiController look like this:
$post = \App\Post::find($request->id);
$social = SocialPost::where([['user_id', '=', ($request->user_id)],['post_id', '=', ($request->id)]])->first();
$unsocial = SocialPost::where([['user_id', '=', ($request->user_id)],['post_id', '=', ($request->id)],['like', '=', 0]])->first();
if ($social) {
if ($unsocial) {
$social->update(['like' => 1]);
return json_encode(array('status' => true,'msg'=>'like'));
}
else {
$social->update(['like' => 0]);
return json_encode(array('status' => true,'msg'=>'dislike'));
}
}
else {
$join = new \App\SocialPost;
$join->user_id = $request->user_id;
$join->post_id = $post->id;
$join->like = 1;
$join->view = 0;
$join->creator = 1;
$join->save();
return json_encode(array('status' => true,'msg'=>'New table'));
}
The problem is that the first If statement works but the second doesn't. If the row already exists he always put '1' for 'like' also if the message that return is 'dislike'.

Here is an example that should work with you.
<?php
// Get the post from the database
$post = \App\Post::find($request->id);
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
// Declare an empty variable that will determine if
// the post is being "liked" or "disliked"
$postAction = '';
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// The post has at least 1 like
$postAction = 'dislike';
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// The post has 0 likes
$postAction = 'like';
// Increment the likes by 1
$socialPost->increment('likes', 1);
}
// Determine if this was a new SocialPost record
if ($socialPost->wasRecentlyCreated)
{
// Override the post action as "New table"
$postAction = 'New table';
}
// Return the goods
return json_encode(['status' => true, 'msg' => $postAction]);
Explanation
You can determine if the SocialPost record exists, or create a new one - all in a single line using firstOrCreate referenced in the documentation here. The first array parameter takes in what you are looking for, and the second array paramater takes in what should be created if the first parameter turned up nothing
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
Then you can clean up the adding or subtracting likes by using increment or decrement referenced in the documentation here.
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// Increment the likes by 1
$socialPost->increment('likes', 1);
}

Related

Laravel multiple where clause checking for null values through a variable

I am storing a where clause in a variable
if($condition === 1) {
$whereClause = ['mID' => NULL, 'qid' => $listing->lID, 'deleted' => false];
}
else {
$whereClause= ['mID' => $member->mID, 'qid' => $listing->lID, 'deleted' => false];
}
And I get the collection via
$collection = Model::where($whereClause)
BUT on the first condition, I actually want the mID to be either 0 or NULL, I want to retrieve items where mID can be 0 or NULL, so I want orWhere clause, which I did use as shown below, but this does not work, gives an error of memory exhausted so something went wrong
if($condition === 1) {
$whereClause = ['mID' => NULL, 'qid' => $listing->lID, 'deleted' => false];
$orWhereClause = ['mID' => 0, 'qid' => $listing->lID, 'deleted' => false];
$collection = Model::where($whereClause)->orWhere($orWhereClause)
}
else {
$whereClause= ['mID' => $member->mID, 'qid' => $listing->lID, 'deleted' => false];
$collection = Model::where($whereClause)
}
Any ideas of how I can achieve this sort of where condition
This seems like the easiest method. Chaining where() methods is the same as passing them in as an array.
$collection = Model::where('qid', $listing->lID)->where('deleted', false);
if($condition === 1) {
$collection = $collection->whereIn('mID', [0, NULL]);
}
else {
$collection = $collection->where('mID', $member->mID);
}
(Note that according to the documentation, if you wanted to pass an array to the where() method, you were doing it wrong.)
Miken32 is correct, but the code could be written in a single query instead of adding the where() in an if/else statement:
$collection = Model::where('qid', $listing->lID)->where('deleted', false)
->when($condition === 1, function($q){
$q->whereIn('mID', [0, NULL]);
})->when($condition !== 1, function($q){
$q->where('mID', $member->mID);
});
Except for the missing of ";", i think that you should implement it in this way:
$whereClause = [['mID', NULL], ['qid' , $listing->lID] , ['deleted', false]];
$orWhereClause = [['mID', 0], ['qid' , $listing->lID] , ['deleted', false]];
$collection = Model::where($whereClause)->orWhere($orWhereClause);
and if you need other condition, just push an array in the right array where the first parameter is the field and the second the value, or first parameter is the field, the second the operator and the third the value

Check record if exist using updateOrCreate and do a math(SUM) if record exist in laravel 5.5

I have a store function that saves array items into my items table and together with that I am trying to check if the product_is is already in my Warehouse1StockSummaries. if still not, I will grab the product_id and its qty, If its there already then I want to ADD the value from the 'stock_in_qty' which is inside the array to the 'qty_in' in my Warehouse1StockSummaries. I hope my explanation make sense to you :)
here's my code.
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['stock_in_qty']); $i++) {
if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
'stock_in_qty' => intval($input['stock_in_qty'][$i]),
'stock_out_qty' => $input['stock_out_qty'][$i],
'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i]
];
$product_id = $input['product_id'][$i];
$qty_in = intval($input['stock_in_qty'][$i]);
// dd($qty_in);
// ADD stock_in_qty TO QTY_IN ????
$stockSummary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $product_id ],
['qty_in' => $qty_in,
'qty_out' => null
]);
// dd($stockSummary);
array_push($items, Warehouse1stocks::create($acceptItem));
}
return redirect()->route('orders.index');
}
I check and everything is ok the only missing is the part where I need to grab the value from 'stock_in_qty' and add to 'qty_in' if the product id is already found in Warehouse1StockSummaries. Thank you so much in advance!
You could use the wasRecentlyCreated property on the model to determine if the model has just been created or not. If it hasn't then it won't have used $qty_in value, this means you could then use the increment() to add to the existing value in the database:
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $product_id ],
['qty_in' => $qty_in, 'qty_out' => null]
);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $qty_in);
}

Silverstripe ignoring NULL filter in get command

We have a Silverstripe project that uses the following logic to find duplicate records:
if ($queryString) {
$duplicate = SavedSearch::get()->filter(array(
'RentOrBuy' => $rentOrBuy,
'MemberID' => $member->ID,
'QueryString' => $queryString,
))->first();
} else {
$duplicate = SavedSearch::get()->filter(array(
'RentOrBuy' => $rentOrBuy,
'MemberID' => $member->ID,
'QueryString' => NULL,
))->first();
}
However this doesn't return the expected responses. When $queryString is NULL it doesn't return any objects - even when QueryString is set as "NULL" on matching fields in the database.
Any ideas about why this is happening/ what is going on?
It's fixed for 4.0 from the looks
https://github.com/silverstripe/silverstripe-framework/pull/4196/commits/922d02f5356d5904debaf10003477cdd00306192
so for now..
if ($queryString) {
$duplicate = SavedSearch::get()->filter(array(
'RentOrBuy' => $rentOrBuy,
'MemberID' => $member->ID,
'QueryString' => $queryString,
))
->first();
} else {
$duplicate = SavedSearch::get()->filter(array(
'RentOrBuy' => $rentOrBuy,
'MemberID' => $member->ID
))
->where('QueryString IS NULL')
->first();
}
Be careful when using where, since it wont do any sql escaping. Here its fine but always use the filter when passing in user data.

Drupal 7 Select query with If condition mysql database

function tablesort_example_page() {
//$date2=date('m-d-Y', strtotime('t.added_date'));
// if('t.status'==1){
// $status='Active';
// }else{
// $status='Inactive';
// }
// We are going to output the results in a table with a nice header.
$header = array(
// The header gives the table the information it needs in order to make
// the query calls for ordering. TableSort uses the field information
// to know what database column to sort by.
array('data' => t('S No'), 'field' => 't.id'),
array('data' => t('Country Name'), 'field' => 't.country_name'),
array('data' => t('Status'), 'field' => 't.status'),
array('data' => t('Added Date'), 'field' => 't.added_date'),
array('data' => t('Action'), 'field' => 't.id',),
array('data' => t('Action'), '',),
);
// Using the TableSort Extender is what tells the the query object that we
// are sorting.
$limit = 10;
$query = db_select('countries', 't')->extend('TableSort')->extend('PagerDefault')->limit($limit)->orderby('id', ASC);
$query->fields('t');
// Don't forget to tell the query object how to find the header information.
$result = $query
->orderByHeader($header)
->execute();
if('$row->status'==0){
$status='Active';
} else {
$status='Inactive';
}
$rows = array();
$i=1;
foreach ($result as $row) {
//print_r($row);
// Normally we would add some nice formatting to our rows
// but for our purpose we are simply going to add our row
// to the array.
$rows[] = array(
$row->id,
$row->country_name,
$status, ----> **
here i need to execute the If condition for $status
//$row->added_date,
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);
$i++;
}
As per my database table the below are my table fields.
(id, country_name, status, added_date)
In Status there will be 0 or 1
now my Question is i need to display status
if 0 - Inactive
1 - Active
I'd suggest using a PHP ternary operator to test the value in the status field and output a string description based on that value.
$rows[] = array(
$row->id,
$row->country_name,
($row->status == 0) ? 'Inactive' : 'Active',
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);

Error in getting the last inserted ID of a query using batch insert in CodeIgniter

How can I get the last inserted ID of a query using the batch insert in CodeIgniter. I used the code $this->db->insert_id() but it returns the ID of my first inserted array. I can't get the last insert.
Here's what I did:
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders[] = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
}
$this->db->insert_batch('po_order', $orders);
echo $this->db->insert_id(); //will return the first insert array
I can't spot where's my error. My last option is to get it using a query. I also did mysql_insert_id() but always returns to 0.
I think the best way would be to use the batch insert instead of individual inserts in a loop for performance , but to get the last insert id, ADD the First Insert ID & the Affected Rows.
$this->db->insert_batch('po_order', $orders);
$total_affected_rows = $this->db->affected_rows();
$first_insert_id = $this->db->insert_id();
$last_id = ($first_insert_id + $total_affected_rows - 1);
You will need to do something like this,
$insertIds = array();
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
$this->db->insert('po_order', $orders);
$insertIds[$x] = $this->db->insert_id(); //will return the first insert array
}
print_r($insertIds); //print all insert ids

Categories