Can not use where clause after using with clause in Laravel query - php

I am writing a query using with and then where clause in laravel.
$users = User::query()->with('roles')->where('name', '!=', 'customer')->get();
return $users;
But where clause is not working here. Customers are not excluded. I am providing the snap shot of the query result.

I think you need whereHas() :
use Illuminate\Database\Eloquent\Builder;
$users = User::query()
->with('roles')
->whereHas('roles', function (Builder $query) {
$query->where('name', '!=', 'customer');
})
->get();
return $users;

I suppose you trying to filter relation data in base query.
Try smth like that:
$users = User::query()->with([
'roles' => function ($q) {
$q->where('name', '!=', 'customer');
}])
->get();
return $users;
Doc

Related

Join 2 tables in a Single Eloquent Laravel using multiple where clause

here I'd like to find the solution to simplify my query to get data using eloquent in Laravel.
$room_id = Booking::whereBetween('from', [$request->from, $request->to])
->orWhereBetween('to', [$request->from, $request->to])
->where('from', '<=', $request->from, )
->where('to', '>=', $request->from)
->pluck('room_id');
$rooms = Room::whereNotIn('id', $room_id )->get();
So here I have 2 Eloquent operations to get Rooms which not included in the Booking Table with specified requirements. So far I have no problem with it, but can you guys give me best practice to simplify from what I do? Thank you.
Make sure that 'bookings' relation is written on your Room model.
$rooms = Room::whereDoesntHave('bookings', use($request) function($q){
$q->whereBetween('from', [$request->from, $request->to])
$q->orWhereBetween('to', [$request->from, $request->to])
$q->where('from', '<=', $request->from, )
$q->where('to', '>=', $request->from)
})->get();
Your can refer laravel relationship to add it in model and after that using whereHas to query join table:
https://laravel.com/docs/9.x/eloquent-relationships
Example:
With options
protected $with = [
'product_savour'
];
Relationship
public function product_savour()
{
return $this->hasMany(ProductSavour::class, 'product_id');
}
Query
$productQuery->whereHas('product_savour', function ($query) use ($filters) {
$query->whereHas('savour', function ($query) use ($filters) {
$query->whereHas('type', function ($query) use ($filters) {
$query->whereIn('id', $filters['savour']);
});
});
});

Laravel with() and search using LIKE not working

So I have 2 tables, 1 table for storing debt(id, amount, category_id) and 1 table for storing debt categories(id, name). I am trying to pull the data for each month from the debt table, but I also have a search which seems to not work, I guess I am missing something.
I have the following:
$debt = $this->debtModel
->select(DB::raw('MONTH(created_at) as month'), DB::raw('SUM(amount) as amount'), 'category_id')
->where('user_id', Auth::user()->id)
->whereYear('created_at', $year)
->with(['category' => function ($query) use ($filter) {
$query->where('name', 'like', "%$filter%");
}])
->orderBy('month', 'asc')
->groupBy('month')
->groupBy('category_id')
->get();
Debt Model:
public function category()
{
return $this->hasOne('App\Models\DebtCategory', 'id', 'category_id');
}
This works fine, with the exception of search, If I try to filter by a category name it still returns everything.
try with
->whereHas('category' , function ($query) use ($filter) {
$query->where('name', 'like', "%$filter%");
})
instead of
->with(['category' => function ($query) use ($filter) {
$query->where('name', 'like', "%$filter%");
}])
with() will just loads the relationship not filtering result.

Laravel Eloquent hardcoded value in whereNotIn

In Laravel eloquent query using multiple columns for whereNotIn clause I need to hardcoded one of the DB::raw column for the value should be coming from a variable (loop variable). What is the best way to implement this?
This is my query and I need to change the hardcoded 1 in DB::raw('(1,user_profile.user_id')
$otherProfiles = Userprofile::where('user_id', '!=', $profile->user_id)
->where(function ($query) use ($userInterests) {
foreach ($userInterests as $interest) {
$query->orWhere('interest', 'like', "%$interest%");
};
})
->whereNotIn(DB::raw('(1, user_profile.user_id)'), function ($query) {
$query->select('sender_id', 'receiver_id')
->from('email_reports');
})
->inRandomOrder()
->get();
Manage to fix it by just simple concatenation
the code added were DB::raw('('. $profile->user_id . ', user_profile.user_id)')
create a variable as $id for your dynamic value..
$otherProfiles = Userprofile::where('user_id', '!=', $profile->user_id)
->where(function ($query) use ($userInterests) {
foreach ($userInterests as $interest) {
$query->orWhere('interest', 'like', "%$interest%");
};
})
->whereNotIn('user_id', $id), function ($query) {
$query->select('sender_id', 'receiver_id')
->from('email_reports');
})
->inRandomOrder()
->get();

Laravel Collection Query, Where I am going wrong?

My tables looks like this
area_trip
|id|dispatch_id|trip_id|status|
equipment_trip
|equipment_id|trips_id|dispatch_id|
trips
|id|dispatch_id|status
I am trying to pass collection to my resource. Can someone check my query and tell me what I am doing wrong as following query returning all the data matches dispatch_id whether it matches equipment_id or not. Btw I am new to laravel.
return
Resources::collection(
area_trip::where('dispatch_id', $request->dispatch_id)
->where('status', 1)
->orWhere('status', 9)
->whereHas('equipment_trip', function($query) use ($request) {
$query->where('equipment_trip.equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());
Here is the relationship set up in area_trip model
public function equipment_trip()
{
return $this->belongsTo(equipment_trip::class, 'trip_id', 'trips_id');
}
I believe your whereHas sub query is incorrect also instead of where and orWhere use where in and you can define all statuses necessary, try this:
Resource::collection(area_trip::where('dispatch_id', $request>dispatch_id)
->whereIn('status', [1, 9])
->whereHas('equipment_trip', function($query) use ($request) {
return $query->where('equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());

whereHas query in Laravel

Hello guys,
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->whereHas('filters', function ($query, $filterArray) {
$query->whereIn('filter_id', $filterArray);
})
->orderBy('products.' . $sort, $sortOrder)
->get();
}
I have the following query and I'm having some issues on the whereHas method. I'm getting an error
Unknown column 'has' in 'where clause
most likely because the $filterArray variable is out of scope for the function ( or at least that is what I am guessing. Any help on how to solve the issue is appreciated.
You cannot use whereHas method in the Query Builder context. The whereHas method is only for Eloquent Query Builder that is comming from the Eloquent models and their relationships.
What you can do is to use joins. So you can try like this:
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->join('filters', 'products.filter_id', '=', 'filters.filter_id')
->whereIn('filter_id', $filterArray);
->orderBy('products.' . $sort, $sortOrder)
->get();
I don't know how you connecting these two tables so here is only the example data:
->join('filters', 'products.filter_id', '=', 'filters.filter_id')

Categories