Multiple query is giving empty data if (true) {
$musicDepartment = $departments->where(function($query) {
$query->where('type', 'music');
})->with(['students'])->get();
$artDepartment = $departments->where(function($query) {
$query->where('type', 'art');
})->with(['students'])->get();
$languageDepartment = $departments->where(function($query) {
$query->where('type', 'language');
})->with(['students'])->get();
}
after If dd($languageDepartment) is giving null but data is not empty. how can I achieve all the there query data? TIA
@deepu07 Why not just like this
$musicDepartment = Department::with('students')->where('type', 'music')->get();
$artDepartment = Department::with('students')->where('type', 'art')->get();
$languageDepartment = Department::with('students')->where('type', 'language')->get();
When duplicating objects like this, you need to clone them. The where clauses are getting replicated on each object, which is why there are no results:
if (true) {
$musicDepartment = clone $departments->where(function($query) {
$query->where('type', 'music');
})->with(['students'])->get();
$artDepartment = clone $departments->where(function($query) {
$query->where('type', 'art');
})->with(['students'])->get();
$languageDepartment = clone $departments->where(function($query) {
$query->where('type', 'language');
})->with(['students'])->get();
}
More reading on cloning here: https://www.php.net/manual/en/language.oop5.cloning.php
@michaloravec I tried like what you suggest dd($languageDepartment) is getting null but it is not null.
@joefusco Tried with Clone still getting empty for last two variables except $musicDepartment
@deepu07 What is happening to the $departments variable before it hits this block? I assume you are replicating the query object because there are additional clauses that should be applied to each of these queries?
@deepu07 If you try this you should get your data or empty collection but not null
$languageDepartment = Department::with('students')->where('type', 'language')->get();
dd($languageDepartment);
@michaloravec I'll get data for dd($languageDepartment);
if I comment this line
$musicDepartment = Department::with('students')->where('type', 'music')->get();
@deepu07 Post your whole code, because it's not possible what did you say.
It worked i did like this
$query1 = $departments;
$query2 = clone $query1;
$query3 = clone $query2;
$musicDepartment = $query1->where('type', 'music')->with('students')->get();
$artDepartment = $query2->where('type', 'art')->with('students')->get();
$languageDepartment = $query3->where('type', 'language')->with('students')->get();
Learned New stuff. Thanks, @michaloravec @joefusco
@deepu07 And what do you have in your $departments?
Please sign in or create an account to participate in this conversation.