Laravel Undefined variable, even after setting isset [duplicate] - php

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

Related

whereHas filter query issue on laravel

hello guys i want result like i have many products and in products have many supplier and one customer so when i search product description than display all product but i want output like product display but match with customer id
$pi = Product::where('customer_id',$customerId)
->whereHas('supplier', function (Builder $query) use($search) {
$query->where('sys_state', '!=', '-1')
->orWhere('name','LIKE','%' . $search . '%');
})
->where('sys_state','!=','-1')
->orWhere('prd_our_item_no', 'LIKE', '%' . $search . '%')
->orWhere('prd_supplier_item', 'LIKE', '%' . $search . '%')
->orWhere('prd_description','LIKE','%' . $search . '%')
->get();
i try this query but all the product display when i search customer id where condition not work
i try to wrap orwhere but noting can search on it
$pi = Product::where('customer_id', $customerId)
->where('sys_state', '!=', '-1')
->whereHas('supplier', function (Builder $query) use ($search) {
$query->where('sys_state', '!=', '-1')
->orWhere(function ($query) use ($search) {
$query->where('name', 'LIKE', '%' . $search . '%')
->where('sys_state','!=','-1');
});
})
->orWhere(function ($query) use ($search, $customerId) {
$query->where('prd_description', 'LIKE', '%' . $search . '%')
->where('sys_state', '!=', '-1')
->where('customer_id',$customerId);
})
->orWhere(function($query) use($search, $customerId){
$query->where('prd_supplier_item', 'LIKE', '%' . $search . '%')
->where('sys_state', '!=', '-1')
->where('customer_id',$customerId);
})
->orWhere(function($query) use($search, $customerId){
$query->where('prd_our_item_no', 'LIKE', '%' . $search . '%')
->where('sys_state', '!=', '-1')
->where('customer_id',$customerId);
})
->get();

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

PHP Laravel search multiple tables with multiple keywords from multiple inputs

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

Laravel Query with subquery not working

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

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