Call to a member function where() on array session - laravel

When I add to the cart I get this error
I'm trying to add a product's into my cart. I've looked for an answer for this everywhere and the results said I just needed to add a return statement in my function. But I already have a return statement and it still doesn't work.
CartService.php
public function count($key)
{
if (!$this->has($key)) return 0;
return $this->get($key)['quantity'];
}
public function has($key)
{
if($key instanceof Model) {
return ! is_null(
$this->cart->where('subject_id' , $key->id)->where('subject_type' , get_class($key))->first()
);
}
return ! is_null(
$this->cart->firstWhere('id' , $key)
);
}

I think this error is just because of cart variable is a array not a collection.
And when you apply where method on cart variable you need to convert cart variable as collection to apply method.
For that your has function may be like this:
public function has($key)
{
$cart = collect($this->cart);
if($key instanceof Model) {
return ! is_null(
$cart->where('subject_id' , $key->id)->where('subject_type' , get_class($key))->first()
);
}
return ! is_null(
$cart->firstWhere('id' , $key)
);
}

Related

Laravel API delete row from db

While trying to delete rows by id from db as below , I am getting the error- count(): Parameter must be an array or an object that implements Countable. I think no id is passed to the delete() function in my code and am not sure how to pass it. Please help me with ur suggestions.
Controller
public function delete($id){
$data = PersonalDetails::where('id',$id)->delete();
// dd($data);
if(count($data)){
return response()->json(['message'=>'Successfully Deleted']);
}
else{
return response()->json(['message'=>'Delete Failed']);
}
}
Route
Route::group([
'namespace'=>'App\Http\Controllers',
'middleware' => 'api',
], function ($router) {
Route::post('delete/{id}', 'PersonalDetailsAdmin#delete');
}
The ->delete() method already returns the count of the deleted rows, so the solution would be:
public function delete($id){
$count = PersonalDetails::where('id',$id)->delete();
// dd($data);
if($count > 0 ){
return response()->json(['message'=>'Successfully Deleted']);
}
else{
return response()->json(['message'=>'Delete Failed']);
}
}

Cant figure out joins

So I am making a Businesses web app with the filters feature. There are two filters that I have problem with: Order By and Attributes(Has following attributes) features. Which looks like this:
Order By
Highest Rated (radio button)
Most reviews (radio button)
Attributes
Accepts Credit Cards (checkbox)
Accepts Events (checkbox)
Alcohol (checkbox)
Delivery (checkbox)
Smoking (checkbox)
So when Order By option is clicked this function is executed. Where $term is value of order_by get request parameter.
BusinessFilter.php
public function orderby($term)
{
if ($term == 'reviews_count') {
return $this->builder
->leftJoin('reviews', 'businesses.id', '=', 'reviews.business_id')
->groupBy('businesses.id')
->selectRaw('businesses.*, COUNT(reviews.id) as reviews_count')
->orderByDesc('reviews_count');
} else if ($term == 'rating') {
return $this->builder
->leftJoin('reviews', 'businesses.id', '=', 'reviews.business_id')
->groupBy('businesses.id')
->selectRaw('businesses.*, AVG(reviews.rating) AS average')
->orderByDesc('average');
} else {
return $this->builder;
}
}
It works ok and the result is correct.
Now when Attribute have some check boxes this function is executed where $term is an array with set of ids.
BusinessFilter.php
public function attributes($term)
{
$attributes= json_decode($term);
if (count($attributes) == 0) {
return $this->builder;
}
return $this->builder
->select('businesses.*')
->join('business_attribute_value', 'businesses.id', '=', 'business_attribute_value.business_id')
->join('values', 'business_attribute_value.attribute_value_id', '=', 'values.id')
->whereIn('values.id', $attributes)
->groupBy('businesses.id')
->havingRaw('COUNT(*) = ?', [count($attributes)]);
}
the result is correct here too.
Now the problem is when both filters have values it executes both queries together and It doesn't return the correct result. I assume it has something to do with joins. Am I doing something wrong? Please help. And if you need more info or code please let me know. Thank you, you are the best guys!
This is how I execute filters
public function getSearch(BusinessFilter $filters)
{
$businesses = Business::filter($filters)->paginate(30);
return $businesses;
}
This is QueryFilter class. Basically what it does is that it goes through each request parameter and executes its function that was mentioned above.
class QueryFilters{
protected $request;
protected $builder;
public function __construct( Request $request )
{
$this->request = $request;
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach( $this->filters() as $name => $value ){
if( !method_exists($this, $name ) ){
continue;
}
if(strlen($value)){
$this->$name($value);
} else {
$this->$name();
}
}
return $this->builder;
}
public function filters()
{
return $this->request->all();
}
}

Codeigniter 3: Is there any 'where' condition added to the Query Builder so far?

I'm using CodeIgniter 3. I just need to know if there is a 'where' condition added to the query builder until now.
I'm calling a 'delete' function that deleted rows from database And it's possible to add a where condition before calling that function. Something like this:
public function delete()
{
// Here I need to know if where condition added to the db class
$this->db
->where('field', 1)
->delete('my_table');
}
public function main()
{
$this->db->where('field2', 2);
$this->delete();
}
In controller
function delete_row()
{
$this->load->model('model_name');
// Pass the id or something else to the row_delete() method
$this->model_name->row_delete($id);
}
In Model
function row_delete($id)
{
$this->db->where('id', $id);
$this->db->delete('table_name');
}
According to your example:
public function delete_method($condition,$table_name )
{
$this->db->where($condition)
$this->db->delete($table_name);
}
public function main()
{
$condition = [
'field1'=>1,
'field2'=>2
];
$table_name = 'my_table';
$this->delete_method($condition,$table_name );
}
I found a solution.
The only thing I need to do is getting a select query and search for 'where' clause inside it:
public function delete()
{
// Here I need to know if where condition added to the db class
$sql = $this->db->get_compiled_select(NULL, FALSE);
$has_where = stripos($sql, 'where') !== FALSE;
// $has_where is TRUE if there is a where condition defined until now
$this->db
->where('field', 1)
->delete('my_table');
}
public function main()
{
$this->db->where('field2', 2);
$this->delete();
}

How to apply the promotion code only once for a product in laravel

I need to apply the promotion code only once for a product, when I apply the same code for the same product it should not get applied.
Find below the code :
public function apply_promo(Request $request)
{
$name = $request->input();
$code=$name['code'];
$code_flags=0;
$p_id='';
$discount_value=0;
$discount_type='';
$Object = new Promotion();
$response = $Object->GetPromotion();
//print_r($response);exit;
foreach($response['promotions']['promotion'] as $value)
{
if($value['code']==$code)
{
$code_flags=1;
$p_id=$value['requires'];
$discount_value=$value['value'];
$discount_type=$value['type'];
}
}
if($code_flags==1)
{
$p_id_array=explode(',',$p_id);
$flags=0;
$data=json_encode(Cart::content());
$cartdata=json_decode($data);
//echo "<pre>";print_r($cartdata);exit;
foreach($cartdata as $key => $value)
{
if($value->options->package != 'domain')
{
if(in_array($value->options->gid,$p_id_array))
{
$flags=0;
$price=$value->price;
if($discount_type=='Percentage')
{
$discount_p=(($price*$discount_value)/100);
$price=$price-$discount_p;
$value->options->discount_code = $code;
$value->options->discount_price = $discount_p;
$value->options->discount_percentage = $discount_value;
Cart::update($value->rowId, ['price' => $price]);
}
}
}
}
if($flags==0)
{
session()->put('promo_code', $code);
\Session::flash('message');
return redirect('cart?success');
}
}
else{
session()->put('promo_code', '');
\Session::flash('message_error');
return redirect('cart?error');
}
}
I have tried using the above code, but here the code getting applied as many times as i submit the code. Kindly suggest me a solution to solve this.
you can make table the have used promotions and their product , say we name it product_promotions have ( promo_id , product_id ) .
then in product model create relation called promocodes (many to many)
public function promocodes(){
return $this->belongsToMany(Promo::class)->withPivot(['promo_id']);
}
this relation will return all promos used by this products so we now able to check if promo used before by it using this code
$product->promocodes()->where('promo_id' , $your_promo_code_id)->exists();

Laravel 5.5 using Scope in model returns error for undefined method

When I try to use scope in this situation, returns me this error:
Call to undefined method Illuminate\Database\Query\Builder::isPromotionTypeIdScope() (View: C:\MAMP\htdocs\mysite\resources\views\site\home.blade.php)
Logic is:
If I replace isPromotionTypeIdScope() with all of the clauses (from the scope), works, but if I use scope gives me error, any suggestions?
Something about the structure is not working. I'm using scopes in another models and have no issues with them. Cannot find what's wrong.
is it possible to be, because I'm trying to add scope (Example: ->promotion()->isPromotionTypeIdScope($promotion_type_id))?
public function product()
{
return $this->belongsTo('App\Models\Product', 'product_id');
}
public function promotion(){
return $this->belongsToMany('App\Models\Promotion', 'promotion_product_prices', 'product_price_id', 'promotion_id');
}
public function single_promotion($promotion_type_id = 0){
return $this->promotion()->isPromotionTypeIdScope($promotion_type_id)->first() ?? false;
}
public function category_promotion($promotion_type_id = 0){
return $this->product()->first()
->category()
->first()
->promotion()
->isPromotionTypeIdScope($promotion_type_id)
->first() ?? false;
}
public function full_promotion($promotion_type_id = 0)
{
return Promotion::where('full', 1)->isPromotionTypeIdScope($promotion_type_id)->first() ?? false;
}
public function hasPromotion($promotion_type_id = 0){
if($this->full_promotion($promotion_type_id) !== false){
return $this->full_promotion($promotion_type_id);
}elseif($this->category_promotion($promotion_type_id) !== false){
return $this->category_promotion($promotion_type_id);
}elseif($this->single_promotion($promotion_type_id) !== false){
return $this->single_promotion($promotion_type_id);
}else{
return false;
}
}
public function scopeIsPromotionTypeIdScope($query, $promotion_type_id=0){
if($promotion_type_id != 0){
return $query->where('promotion_type_id', $promotion_type_id)
->where('validity_from', '<=', date('Y-m-d H:i:s'))
->where('validity_to', '>=', date('Y-m-d H:i:s'))
->where('active', 1)
->orderBy('updated_at', 'DESC')->limit(1);
}else{
return $query;
}
}
Everywhere you call your isPromotionTypeIdScope method on Promotion model so you should define scopeIsPromotionTypeIdScope in Promotion model instead of this one.

Resources