Laravel Query with subquery not working - php

Maybe I am doing this incorrectly, however what I want to do logically is this:
I want to first select all posts that contain a certain string.
Then from those results, I want to narrow it down to only posts within a certain date (Y|m|d).
So this is what im doing at the moment:
$results = DB::table('posts');
if ($query == null){
$query = "Posted On: " . $date;
}else {
$results->where('posts.title', 'LIKE', "%$query%")
->orWhere('posts.meta_description', 'LIKE', "%$query%")
->orWhere('posts.meta_keywords', 'LIKE', "%$query%")
->orWhere('posts.body', 'LIKE', "%$query%")
->orWhere('posts.seo_title', 'LIKE', "%$query%");
$query = $query." / Posted On: " . $date;
}
$results->where(function($query) use ($date){
$date = explode('-', $date);
if (!isset($date[1])){
$query->whereYear('created_at', '=', $date[0]);
}else if(isset($date[1]) && !isset($date[2])){
$query->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1]);
}else if (isset($date[1]) && isset($date[2])){
$query->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1])
->whereDay('created_at', '=', $date[2]);
}
});
$results = $results->paginate($this->paginate_size());
However, this query is still just returning anything that contains the query string and ignoring the fact that I want to select a subset that are only posts on a specific year/month/day.
What am I missing?
Edit:
Using $results->toSql(); I get the query:
select * from `posts` where `posts`.`title` LIKE ? or
`posts`.`meta_description` LIKE ? or `posts`.`meta_keywords` LIKE ? or
`posts`.`body` LIKE ? or `posts`.`seo_title` LIKE ? and year(`created_at`) = ?
However, it is not working...
If I enter for example the query "Lorem" it will find all of the posts with the text Lorem in it.
However, when I add a specific date like just "2015", it should not show ANY posts from 2015 with the query Lorem since it does not exist.
So there is some logic problem here. Any ideas?

You shouldn't need a subquery.
If you have the proper query in place you should be able to access in the same query.
Of course you can have the dynamic where with the conditions, but do it on the same query. Something along the lines, for example:
if ($query == null){
$query = "Posted On: " . $date;
}
$results->where('posts.title', 'LIKE', "%$query%")
->orWhere('posts.meta_description', 'LIKE', "%$query%")
->orWhere('posts.meta_keywords', 'LIKE', "%$query%")
->orWhere('posts.body', 'LIKE', "%$query%")
->orWhere('posts.seo_title', 'LIKE', "%$query%");
$date = explode('-', $date);
if (!isset($date[1])){
$results->whereYear('created_at', '=', $date[0]);
}else if(isset($date[1]) && !isset($date[2])){
$results->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1]);
}else if (isset($date[1]) && isset($date[2])){
$results->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1])
->whereDay('created_at', '=', $date[2]);
}
$results = $results->paginate($this->paginate_size());

You can use the whereDate() Eloquent method:
$results = DB::table('posts');
if ($query == null){
$query = "Posted On: " . $date;
}else {
$results->where(function($q) {
$q->where('posts.title', 'LIKE', "%$query%")
->orWhere('posts.meta_description', 'LIKE', "%$query%")
->orWhere('posts.meta_keywords', 'LIKE', "%$query%")
->orWhere('posts.body', 'LIKE', "%$query%")
->orWhere('posts.seo_title', 'LIKE', "%$query%");
})->whereDate('created_at', '=', date('Y-m-d');
$query = $query." / Posted On: " . $date;
}
$results = $results->paginate($this->paginate_size());

Related

I want to filter single value or multiple value in Laravel controller

I want to filter one value or multiple values in the Laravel controller
$news_paper_machine_ads = newsPaperMachineAds::join('news_paper_district', 'news_paper_district.idnews_paper_district', '=', 'news_paper_machine_ads.news_paper_district_id')
->join('news_paper_city', 'news_paper_city.idnews_paper_city', '=', 'news_paper_machine_ads.news_paper_city_id')
->join('news_paper_machine_field', 'news_paper_machine_field.idnews_paper_machine_field', '=', 'news_paper_machine_ads.news_paper_machine_field_id')
->where('district', 'LIKE', '%' . $district . '%')
->where('news_paper_city', 'LIKE', '%' . $city . '%')
->where('machine_field', 'LIKE', '%' . $machine_field .'%')
->get();
I want to filter this query past district value(only district data)
city = only city data
machine field = only machine field data
pass district and city = only district and city data
pass district and machine field= only district and machine field data
pass district, city and machine field = only district, city and machine field data
Please help me solve this problem.
$news_paper_machine_ads = newsPaperMachineAds::join('news_paper_district', 'news_paper_district.idnews_paper_district', '=', 'news_paper_machine_ads.news_paper_district_id')
->join('news_paper_city', 'news_paper_city.idnews_paper_city', '=', 'news_paper_machine_ads.news_paper_city_id')
->join('news_paper_machine_field', 'news_paper_machine_field.idnews_paper_machine_field', '=', 'news_paper_machine_ads.news_paper_machine_field_id')
->where(function($query) use($district,$city,$machine_field){
if($district){
$query->where('district', 'LIKE', '%' . $district . '%');
}
if($city){
$query->where('news_paper_city', 'LIKE', '%' . $city . '%');
}
if($machine_field){
$query->where('machine_field', 'LIKE', '%' . $machine_field . '%');
}
})
->get();
use when and OrWhere query like this
$news_paper_machine_ads = newsPaperMachineAds::join('news_paper_district', 'news_paper_district.idnews_paper_district', '=', 'news_paper_machine_ads.news_paper_district_id')
->join('news_paper_city', 'news_paper_city.idnews_paper_city', '=', 'news_paper_machine_ads.news_paper_city_id')
->join('news_paper_machine_field', 'news_paper_machine_field.idnews_paper_machine_field', '=', 'news_paper_machine_ads.news_paper_machine_field_id')
->when($district, function ($query) use ($district) {
return $query->orWhere('district', 'LIKE', '%' . $district . '%');
})
->when($city, function ($query) use ($city) {
return $query->orWhere('news_paper_city', 'LIKE', '%' . $city . '%');
})
->when($machine_field, function ($query) use ($machine_field) {
return $query->orWhere('machine_field', 'LIKE', '%' . $machine_field .'%');
})->get();
$district = $request->district;
$city = $request->city;
$machine_field = $request->machine_field;
$data_arry = array();
if ($district != "Select") {
$data_arry["district"] = $district;
}
if ($city != "Select") {
$data_arry["city"] = $city;
}
if ($machine_field != "Select") {
$data_arry["machine_field"] = $machine_field;
}
$news_paper_machine_ads = newsPaperMachineAds::join('news_paper_district', 'news_paper_district.idnews_paper_district', '=', 'news_paper_machine_ads.news_paper_district_id')
->join('news_paper_city', 'news_paper_city.idnews_paper_city', '=', 'news_paper_machine_ads.news_paper_city_id')
->join('news_paper_machine_field', 'news_paper_machine_field.idnews_paper_machine_field', '=', 'news_paper_machine_ads.news_paper_machine_field_id')
->where(function ($query) use ($data_arry) {
if (isset($data_arry['district'])) {
$query->where('district', $data_arry['district']);
}
if (isset($data_arry['city'])) {
$query->where('news_paper_city', $data_arry['city']);
}
if (isset($data_arry['machine_field'])) {
$query->where('machine_field', $data_arry['machine_field']);
}
})
->get();

Laravel Undefined variable, even after setting isset [duplicate]

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);
});
}

Laravel-5.6 'LIKE' in where select

I use this query and i get a error :
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where(['sender_id' => $user_id, "%$description%", 'LIKE','description'])
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}
and this is the error that I get :
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where
clause' (SQL: select * from transcation_historique where
(sender_id = 32 and 0 = %salaire% and 1 = LIKE and 2 =
description) or receiver_id = 32)"
and this what really i want to run:
select * from `transcation_historique` where (`sender_id` = 32 and `description` = %salaire%) or `receiver_id` = 32)
Try this,
$description_query = Transcationhistorique::where(
function($query) use ($user_id, $description){
return $query->where('sender_id', $user_id)
->where('description', 'like', '%' . $description .'%');
}
)
->orWhere('receiver_id', $user_id)
->get();
It seems like your where query is not structured correctly.
You should use the following structure if you want to use operators other than "="
Source
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
My suggestion is:
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where([
['sender_id', '=', $user_id],
['description', 'LIKE', "%{$description}%"]
])
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}
Try this one:
Transcationhistorique::where('receiver_id', '=', $user_id)
->orWhere(function ($query) use ($user_id, $description) {
$query->where('sender_id', '=', $user_id)->where('description', 'LIKE', "%".$description."%");
})->get();
You can use multiple where method as and.
Can you try following codes?
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where('sender_id', $user_id)
->where("description", 'LIKE','%' . $description . '%')
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}

How we can join with where condition result through laravel eloquent?

I have situation in laravel 5.1 with eloquent. That is very hard for me at this time to get the solution.
I have 7 tables in database which are not related to each other, but I want to get results with joining them all and with where clause.
My Tables relations are:
lifegroups -> Campuses -> locations -> address
and
lifegroups -> grouptype -> groupuser -> user // this is confusing little bit
and
lifegroups -> schedule -> recurrance
Notice the lifegroup table is associated with multiple other tables.
My Existing Query is:
$campusGroups = DB::table('campuses')
->Join('lifegroups','campuses.f1_id', '=', 'lifegroups.campusId')
->Join('locations', 'locations.group_id', '=', 'lifegroups.f1Id')
->Join('addresses', 'addresses.location_id', '=', 'locations.id')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct() //'users.first_name', 'users.last_name',
->select('lifegroups.*', 'campuses.name AS campusname', 'addresses.address', 'addresses.address2', 'addresses.city', 'addresses.province');
$groupLeaders = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct()
->select('lifegroups.id', 'users.first_name', 'users.last_name');
$groupRecurrences = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('schedules', 'schedules.event_id', '=', 'lifegroups.eventid')
->Join('recurrences', 'recurrences.schedule_id', '=', 'schedules.id')
->distinct()
->select('recurrences.occurOnFriday', 'recurrences.occurOnSaturday', 'recurrences.occurOnMonday', 'recurrences.occurOnSunday', 'recurrences.occurOnThursday', 'recurrences.occurOnTuesday', 'recurrences.occurOnWednesday', 'recurrences.recurrenceFrequency', 'recurrences.recurrenceFrequencyMonthly', 'recurrences.recurrenceFrequencyWeekly', 'schedules.start_date', 'schedules.recurrence', 'lifegroups.id AS groupId');
if (Session::has('campus')){
$campusId = Session::get('campus');
$searchObj = $campusGroups->where('campuses.id', intval($campusId));
$groupLeaders = $groupLeaders->where('campuses.id', intval($campusId));
$groupRecurrences = $groupRecurrences->where('campuses.id', intval($campusId));
$searchArray['campusId'] = $campusId;
}
if (Session::has('gender')){
$gender = Session::get('gender');
$searchObj = $campusGroups->where('lifegroups.gender', $gender);
$groupLeaders = $groupLeaders->where('lifegroups.gender', $gender);
$groupRecurrences = $groupRecurrences->where('lifegroups.gender', $gender);
$searchArray['gender'] = $gender;
} else {
$searchArray['gender'] = 'N/A';
}
if (Session::has('marital_status')){
$marital_status = Session::get('marital_status');
$searchObj = $campusGroups->where('lifegroups.marital_status', $marital_status);
$groupLeaders = $groupLeaders->where('lifegroups.marital_status', $marital_status);
$groupRecurrences = $groupRecurrences->where('lifegroups.marital_status', $marital_status);
$searchArray['marital_status'] = $marital_status;
} else {
$searchArray['marital_status'] = 'N/A';
}
if (Session::has('age')){
$age = Session::get('age');
$searchObj = $campusGroups->where('lifegroups.startAgeRange', $age);
$groupLeaders = $groupLeaders->where('lifegroups.startAgeRange', $age);
$groupRecurrences = $groupRecurrences->where('lifegroups.startAgeRange', $age);
$searchArray['age'] = $age;
} else {
$searchArray['age'] = 'N/A';
}
if (Session::has('keyword')){
$keyword = Session::get('keyword');
$searchObj = $campusGroups->where('lifegroups.name', 'Like', '%'. $keyword . '%');
//->orWhere('lifegroups.description', 'Like', '%'.$keyword.'%')
//->orWhere('users.first_name', 'Like', '%'.$keyword.'%');
$groupLeaders = $groupLeaders->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$groupRecurrences = $groupRecurrences->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$searchArray['keyword'] = $keyword;
} else {
$searchArray['keyword'] = 'N/A';
}
$campusGroupsTemp = $campusGroups->get();
$campusGroups = [];
$recurrenceGroups = [];
$groupLeaders = $groupLeaders->get();
$groupRecurrences = $groupRecurrences->get();
So this is a very long process and I can't add further search filters. Do you guys have any better idea how to do it with Laravel Eloquent, like
Lifegroups::with(['campuses', 'locations', 'addresses', 'grouptype', 'groupuser', 'users', 'schedules', 'recurrences'])
->where(['lifegroups.name', '=' 'name_value'],['lifegroups.description','like', '%like_valie%'], ['user.first_name', 'like', 'first_name_value'])
->get()->toArray();
If you are confused like me then only let me know how to do below mentioned thing with above type of tables scenario.
This becomes very easy with Eloquent assuming you have your models setup correctly. Just use dot notation to handle the nesting.
$data = Lifegroups::with([
'campuses.locations.address',
['grouptype.groupuser.user', function($q) use ($first_name) {
// Handle the constraints on the users table here.
$q->where('name', 'like', $first_name)
}],
'schedule.recurrance'
])
// Handle any constraints on the Lifegroups table here
->where('name', '=', 'name_value')
->where('description','like', '%like_valie%')
->get();
If you need to add more constraints for different tables, just add another parameter to the array we passed into the with function going as deep as you need to with the nexting and passing in a function with it where you will set the constraints like I did the users table.

Laravel querying database 'AND' 'OR' Where orWhere

In Laravel 4 I have built a search form. Where a person can submit either
email address
From - To date
Ref number
They can only search using one of the above options; As they have to select from a drop down on which they would like to search with. The final code I used to get this working is as follows:
if(Input::get('from') && Input::get('to')){
$records = Applications::where('created_at', '>=', Input::get('from'))
->where('created_at', '<', date('Y-m-d', strtotime(Input::get('to'). ' + 1 days')))
->lists('id');
}elseif(Input::get('email') || Input::get('ref')){
$records = Applications::where('Application_number', '=', Input::get('ref'))
->where('email', '=', Input::get('email'), 'OR')
->lists('id');
}else{
$records = Applications::all()->lists('id');
}
The works for my requirements, but I'm not really happy this is the best solution.
I also tried to use either of the solutions in this thread Laravel 4 eloquent WHERE with OR AND OR?
$result = User::where('created_at', 'LIKE', '%' . $search . '%')
->where('updated_at', 'LIKE', '%' . $search . '%', 'OR')
->where('user_first_name', 'LIKE', '%' . $search . '%', 'AND')
->where('user_any_field', 'LIKE', '%' . $search . '%')->get();
OR
Model::where(function ($query) {
$query->where('a', '=', 1)
->orWhere('b', '=', 1);
})->where(function ($query) {
$query->where('c', '=', 1)
->orWhere('d', '=', 1);
});
But all I kept getting was value can't be null, when searching on from and to; email and ref worked fine.
You can try this:
$input = Input::all();
Model::where(function($query) use ($input) {
if (isset($input['something'])) {
$query->where('some_field_1', '=', $input['something']);
}
if (isset($input['something_else'])) {
$query->where('some_field_2', '=', $input['something_else']);
}
})->get();
I think this is the cleanest way. Of course, you should put the if statements to be of your need.

Categories