I am facing issue to fetch records using offset and limit.
Currently I have 73 records in my database
My body request look like below.
{
"email": "",
"name": "",
"role_id":"",
"pageNumber": 8,
"pageSize": 10
}
Here pageNumber 8 means 7 page because it starts from 0
and page size is 10 means want to show 10 records in page and expected output should be 3 records because there is 3 records between 70 to 80 as my total records is 73 and it should display 3 records.
But its displaying 10 records:
My Code:
$pram = $request->name;
$email= $request->email;
$roleId= $request->role_id;
$pageNumber= $request->pageNumber;
$pageSize= $request->pageSize;
$UserResultQuery = User::with('userBasicInfo','userFacility','roles');
if (!empty($pram)) {
$UserResultQuery->where(function ($query) use ($pram) {
$query->whereHas('userBasicInfo', function ($query1) use ($pram) {
$query1->where('first_name', 'like', '%' . $pram . '%');
$query1->orWhere('middle_name', 'like', '%' . $pram . '%');
$query1->orWhere('last_name', 'like', '%' . $pram . '%');
})->with(['userBasicInfo' => function ($query1) use ($pram) {
$query1->where('first_name', 'like', '%' . $pram . '%');
$query1->orWhere('middle_name', 'like', '%' . $pram . '%');
$query1->orWhere('last_name', 'like', '%' . $pram . '%');
}]);
});
}
if (!empty($roleId)) {
$UserResultQuery->where(function ($query) use ($roleId) {
$query->whereHas('userFacility', function ($query1) use ($roleId) {
$query1->where('role_id', $roleId);
})->with(['userFacility' => function ($query1) use ($roleId) {
$query1->where('role_id', $roleId);
}]);
});
}
if (!empty($email)) {
$UserResultQuery->where('email', 'like', '%' . $email . '%');
}
$results=$UserResultQuery->offset($pageNumber)->limit($pageSize)->get();
$results=$results->toArray(); // here using offset and limit
$totalRecords=count($allUsers);
return response(['status' => true, 'data' => $user_array,'totalRecords' => $totalRecords]);
Pass offset row amount to offset() not page number.
$offset = ($pageNumber - 1) * $pageSize;
$results=$UserResultQuery->offset($offset)->limit($pageSize)->get();
You can also use this forPage(int $page, int $perPage = 15) doc.
$results=$UserResultQuery->forPage($pageNumber, $pageSize)->get();
Related
I have a request('name') and request('surname') that I need to search respectively in 2 columns with this logic:
If request('name'):
request('name') in column name_kanki or in column name_romaji
And if request('surname'):
request('surname') in column surname_kanki or in column surname_romaji.
I only could write the following code to perform the search:
->when($nameSearch, function ($query, $nameSearch) {
return $query->where('name', 'LIKE', '%' . $nameSearch . '%')
->orWhere('name_kanji', 'LIKE', '%' . $nameSearch . '%');
})
->when($surnameSearch, function ($query, $surnameSearch) {
return $query->where('surname', 'LIKE', '%' . $surnameSearch . '%')
->orWhere('surname_kanji', 'LIKE', '%' . $surnameSearch . '%');
})
Now the problem is that the first when() and the second when() seem to be connected to each other by OR logic, while I need AND logic.
At present when I insert for example only the name field, the search works fine, but if I insert both name and surname I get the results added to each other (OR logic).
How can I change this relationship to an AND logic (2 filters) that works if both name and surname fields have been compiled by the user?
Thanks in advance.
Hope this will help you to achieve you AND condition result. instead of when I try with where method.
->where(function ($query) use($nameSearch, $surnameSearch) {
if(isset($nameSearch)){
return $query->where('name', 'LIKE', '%' . $nameSearch .
'%')
->orWhere('name_kanji', 'LIKE', '%' . $nameSearch .
'%');
}else{
return $query->where('surname', 'LIKE', '%' .
$surnameSearch . '%')->orWhere('surname_kanji',
'LIKE', '%' . $surnameSearch . '%');
}
})
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
What's wrong with this code? I also set isset function to not do anything if prop_type is not set but still there it pass ! and then next time its used it shows error Undefined variable: prop_type
btw I am using laravel.
if(isset($prop_type))
{
$Topics= Topic::where('title_en', 'like', '%' . $search_word . '%')->join('topic_fields', function ($join) {
$join->on('topic.id', '=', 'topic_fields.topic_id')
->where('topic_fields.field_id', '=', $prop_type);
})
and this the full function m using !with form !
{
// General Webmaster Settings
$WebmasterSettings = WebmasterSetting::find(1);
$search_word = $request->search_word;
$prop_type = $request->prop_type;
$categori =$request->prop_cat;
$prop_condi =$request->prop_condi;
if (!isset($search_word,$prop_type,$categori,$prop_condi)) {
// count topics by Category
$category_and_topics_count = array();
$AllSections = Section::where('status', 1)->orderby('row_no', 'asc')->get();
if (!empty($AllSections)) {
foreach ($AllSections as $AllSection) {
$category_topics = array();
$TopicCategories = TopicCategory::where('section_id', $AllSection->id)->get();
foreach ($TopicCategories as $category) {
$category_topics[] = $category->topic_id;
}
$Topics = Topic::where([['status', 1], ['expire_date', '>=', date("Y-m-d")], ['expire_date', '<>', null]])->orWhere([['status', 1], ['expire_date', null]])->whereIn('id', $category_topics)->orderby('row_no', 'asc')->get();
$category_and_topics_count[$AllSection->id] = count($Topics);
}
}
// Get current Category Section details
$CurrentCategory = "none";
$WebmasterSection = "none";
// Get a list of all Category ( for side bar )
$Categories = Section::where('father_id', '=',
'0')->where('status', 1)->orderby('row_no', 'asc')->get();
// Topics if NO Cat_ID
$Topics = Topic::where('title_ar', 'like', '%' . $search_word . '%')
->orwhere('title_en', 'like', '%' . $search_word . '%')
->orwhere('seo_title_ar', 'like', '%' . $search_word . '%')
->orwhere('seo_title_en', 'like', '%' . $search_word . '%')
->orwhere('details_ar', 'like', '%' . $search_word . '%')
->orwhere('details_en', 'like', '%' . $search_word . '%')
->orwhere('details_en', 'like', '%' . $search_word . '%')
->orderby('id', 'desc')->paginate(env('FRONTEND_PAGINATION'));
if(isset($categori)){
$Topics= Topic::where('expire_date', '>=', Carbon::now())->join('topic_categories', function ($join) {
$join->on('topic.id', '=', 'topic_categories.topic_id')
->where('topic_categories.section_id', '=', $categori);
})
->orderby('id', 'desc')->paginate(env('FRONTEND_PAGINATION'));
}
if(isset($prop_type))
{
$Topics= Topic::where('title_en', 'like', '%' . $search_word . '%')->join('topic_fields', function ($join) {
$join->on('topic.id', '=', 'topic_fields.topic_id')
->where('topic_fields.field_id', '=', $prop_type);
})
->orderby('id', 'desc')->paginate(env('FRONTEND_PAGINATION'));
}
if(isset($prop_condi))
{
$Topics= Topic::where('title_en', 'like', '%' . $search_word . '%')->join('topic_fields', function ($join) {
$join->on('topic.id', '=', 'topic_fields.topic_id')
->where('topic_fields.field_id', '=', $prop_condi);
})
->orderby('id', 'desc')->paginate(env('FRONTEND_PAGINATION'));
}
// Get Most Viewed
$TopicsMostViewed = Topic::where([['status', 1], ['expire_date', '>=', date("Y-m-d")], ['expire_date', '<>', null]])->orwhere([['status', 1], ['expire_date', null]])->orderby('visits', 'desc')->limit(3)->get();
// General for all pages
$WebsiteSettings = Setting::find(1);
$FooterMenuLinks_father = Menu::find($WebmasterSettings->footer_menu_id);
$FooterMenuLinks_name_ar = "";
$FooterMenuLinks_name_en = "";
if (!empty($FooterMenuLinks_father)) {
$FooterMenuLinks_name_ar = $FooterMenuLinks_father->title_ar;
$FooterMenuLinks_name_en = $FooterMenuLinks_father->title_en;
}
$SideBanners = Banner::where('section_id', $WebmasterSettings->side_banners_section_id)->where('status',
1)->orderby('row_no', 'asc')->get();
// Get Latest News
$LatestNews = Topic::where([['status', 1], ['webmaster_id', $WebmasterSettings->latest_news_section_id], ['expire_date', '>=', date("Y-m-d")], ['expire_date', '<>', null]])->orwhere([['status', 1], ['webmaster_id', $WebmasterSettings->latest_news_section_id], ['expire_date', null]])->orderby('row_no', 'asc')->limit(3)->get();
// Page Title, Description, Keywords
$site_desc_var = "site_desc_" . trans('backLang.boxCode');
$site_keywords_var = "site_keywords_" . trans('backLang.boxCode');
$PageTitle = $search_word;
$PageDescription = $WebsiteSettings->$site_desc_var;
$PageKeywords = $WebsiteSettings->$site_keywords_var;
// .. end of .. Page Title, Description, Keywords
// Send all to the view
return view("frontEnd.topics",
compact("WebsiteSettings",
"WebmasterSettings",
"FooterMenuLinks_name_ar",
"FooterMenuLinks_name_en",
"LatestNews",
"search_word",
"SideBanners",
"WebmasterSection",
"Categories",
"Topics",
"CurrentCategory",
"PageTitle",
"PageDescription",
"PageKeywords",
"TopicsMostViewed",
"category_and_topics_count"));
} else {
// If no section name/ID go back to home
return redirect()->action('FrontendHomeController#HomePage');
}
}```
You must to use the variable:
if(isset($prop_type))
{
$Topics = Topic::where('title_en', 'like', '%' . $search_word . '%')
->join('topic_fields', function ($join) use ($prop_type) { //add more this code
$join->on('topic.id', '=', 'topic_fields.topic_id')
->where('topic_fields.field_id', '=', $prop_type);
});
}
I need to be able to run a where query on a model and multiple of its relations at once. At the moment I am doing it like this, for a single relation
$users = $users->whereHas('contacts', function ($query) use ($request) {
$query->where('name', 'like', '%' . $request->input('filters_search') . '%')
->orWhere('contact_name', 'like', '%' . $request->input('filters_search') . '%');
);
So this searches my user.name and contact.name fields for the search input, but I need to be able to search multiple relations, not just contacts. Something like this
$users = $users->whereHas(['contacts','photos','status'], function ($query) use ($request) {
$query->where('name', 'like', '%' . $request->input('filters_search') . '%')
->orWhere('contact_name', 'like', '%' . $request->input('filters_search') . '%');
);
So that I can search through the user, contacts, photos and status tables/relations for the search input.
What is the cleanest/best way to achieve this?
If you did happen to be searching the same columns in all of your tables, you could extract the closure to a variable:
$closure = function ($query) use ($request) {
$query->where('name', 'like', '%' . $request->input('filters_search') . '%')
->orWhere('contact_name', 'like', '%' . $request->input('filters_search') . '%');
}
But you'd still have to independently query each relationship:
$users->whereHas('contacts', $closure)
->orWhereHas('photos', $closure)
->orWhereHas('status', $closure);
You should try this:
$users = $users->whereHas('photos','status', function($query) {
$query->where('name', 'like', '%' . $request->input('filters_search') . '%');
});
$users = $users->whereHas('contacts', function($query) use ($request) {
$query->where('contact_name', 'like', '%' . $request->input('filters_search') . '%');
});
OR you should try below way:
User::where('name', 'like', '%' . $request->input('filters_search') . '%')
->whereHas('contacts', function($query) use ($request) {
$query->where('contact_name', 'like', '%' . $request->input('filters_search') . '%');
})
->get();
I have two tables in db, "deals" and "deals_meta" connected between them with a foreign key.
In the "deals" table i have general information about a deal like, title, description, category etc., and in the "deals_meta" i have other specific details like, location, number of bedrooms, price, booking date and so on.
I have a form with multiple fields, title, details, booking date, price range and so on.
My problem is that i can't retrieve from db the deals based on the search query.
The code that i use to retrieve the queries looks like this:
$deals = Deals::where('deals_providers', $provider)->where('deal_types', $dealType)->with('meta')
->where(function ($query) use ($terms, $dealType) {
$query->whereHas('meta', function ($query) use ($terms, $dealType) {
$search = $query->where('deal_type', 'like', '%' . $dealType . '%');
if ($terms['location']) {
$search = $query->orWhere('location', 'like', '%' . $terms['location'] . '%');
}
if ($terms['price_from']) {
$search = $query->orWhere('price', '>', '%' . $terms['price_from'] . '%');
}
if ($terms['price_to']) {
$search = $query->orWhere('price', '<', '%' . $terms['price_to'] . '%');
}
if ($terms['departs_from']) {
$search = $query->orWhere('departs_from', 'like', '%' . $terms['departs_from'] . '%');
}
if ($terms['duration']) {
$search = $query->orWhere('duration', 'like', '%' . $terms['duration'] . '%');
}
if ($terms['available_start']) {
$search = $query->orWHere('available_start', 'like', '%' . $terms['available_start'] . '%');
}
if ($terms['available_end']) {
$search = $query->orWhere('available_end', 'like', '%' . $terms['available_end'] . '%');
}
return $search;
});
if ($terms['title']) {
$query->orWhere('title', 'like', '%' . $terms['title'] . '%');
}
if ($terms['details']) {
$query->orWhere('details', 'like', '%' . $terms['details'], '%');
}
})->get();
Debug::data($deals);
If i search for title or details, it returns only the deals that have that title or contains that details but if i search for location or any other meta related term, it returns all the deals results from the db.
What i'm doing wrong or how can i search corectly?
Thank you!
Solved!
This is the code that works for my case!
$deals = Deals::where('deals_providers', $provider)->where('deal_types', $dealType)->with('meta')
->where(function ($query) use ($terms, $dealType) {
$query->whereHas('meta', function ($query) use ($terms, $dealType) {
if ($terms['location']) {
$query->where('location', 'like', '%' . $terms['location'] . '%');
}
if ($terms['price_from'] && $terms['price_to']) {
$query->whereBetween('price', [$terms['price_from'], $terms['price_to']]);
}
if ($terms['departs_from']) {
$query->where('departs_from', 'like', '%' . $terms['departs_from'] . '%');
}
if ($terms['duration']) {
$query->where('duration', 'like', '%' . $terms['duration'] . '%');
}
if ($terms['available_start']) {
$query->where('available_start', 'like', '%' . $terms['available_start'] . '%');
}
if ($terms['available_end']) {
$query->where('available_end', 'like', '%' . $terms['available_end'] . '%');
}
});
if ($terms['title']) {
$query->orWhere('title', 'like', '%' . $terms['title'] . '%');
}
if ($terms['details']) {
$query->orWhere('details', 'like', '%' . $terms['details'], '%');
}
})->get();
Debug::data($deals);
Could someone explain me the reason why is this query not working? I am trying to create a query - where clients name, email or phone match the necessary criteria. However, it seems to work only with one criteria (name or email or phone), not with several ones. That way, I do not get the results needed and I am left with non- filtered list.
Using Laravel 4.1
$q = new Contract;
$q = $q->with(array('lsct' => function($q) {
return $q->select(array('id', 'code'));
}, 'client' => function($q) {
return $q->select(array('id', 'name', 'phone', 'email'));
}));
if(Input::has('search')) {
$criterion = Input::get('search');
$q = $q->where(function($q) use ($criterion) {
$q->where('uid', 'like', '%' . $criterion . '%')->orWhere('car_number', 'like', '%' . $criterion . '%');
})->orWhereHas('lsct', function($q) use($criterion) {
$q->where('code', 'like', '%' . $criterion . '%');
})->orWhereHas('client', function($q) use($criterion) {
$q->where('name', 'like', '%' . $criterion . '%');
// When i try to add condition below, this 'orWhereHas' not working at all
// ->orWhere('phone', 'like', '%' . $criterion . '%')
//->orWhere('latakko_id', 'like', '%' . $criterion . '%');
});
}
Have you tried installing debugbar to show you exactly what your application is querying?
Here is the link for Laravel 4
This might give you some clues if you can actually see what is being queried.