How to include or exclude where statement in Laravel Eloquent - php

I need the same query for two different user roles. Difference is only in one whereNotIn condition.
So for the Basic user it would be:
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->whereNotIn('ChannelName', $sky)
->get();
And for Premium:
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->get();
I know I can do it with simple if statement:
if($user->userRole == "Basic"){
//first $chart2
}
else{
//second $chart2}
but I have a lots of queries where I need just to add or remove this whereNotin condition and rewriting the queries (using if statement) is not a nice solution.

Try scope.
In your TVModel.php:
public function scopeConditionalWhereNotIn($query, $doesUse, $col, $val) {
if($doesUse)
$query->whereNotIn($col, $val);
}
Usage:
$condi = true;//or false.
$chart2 = TVModel::select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->conditionalWhereNotIn($condi, 'ChannelName', $sky)
->get();

Inside your model add this:
public function scopeBasicUser($query,$channel){
return $query->whereNotIn('ChannelName', $channel);
}
and in your controller:
$query = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid);
if($user->userRole == "Basic")
$query = $query->basicUser($channel);
return $query->get();

$userRole = $user->userRole;
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->where(function ($query) use ($userRole){
if($userRole == "Basic"){
$query->whereNotIn('ChannelName', $sky)
}
})
->get();
This code worked for me.

Related

Laravel Where is getting ignored

My laravel "where" is getting ignored it seems. ->where('products.hide_product', '=', 'N')
Any ideas on what I am doing wrong?
$products = Product::join('brands','products.brand_id','=','brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images','products.product_id','=','images.product_id')->where('img_priority','=','1')->orWhere('img_priority', '=', null)
->where('products.hide_product', '=', 'N')->where('products.group_id', '=', $groupID)->orderBy('img_priority','DESC')
->get(array('products.en_71','products.astm','images.file_name','products.product_id','products.product_name','products.collect_part_no','brands.brand_name','categories.cat_name','products.status','images.file_type','products.pop','products.color_label','products.ai_complete'));
You can move the join in a closure an use the first where there:
$products = Product::join('brands', 'products.brand_id', '=', 'brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images', function ($join) {
$join->on('products.product_id','=','images.product_id')
->where('img_priority','=','1')
->orWhere('img_priority', '=', null);
})
->where(
['products.hide_product', '=', 'N'],
['products.group_id', '=', $groupID],
)
->select('products.en_71', 'products.astm', 'images.file_name', 'products.product_id', 'products.product_name', 'products.collect_part_no', 'brands.brand_name', 'categories.cat_name', 'products.status', 'images.file_type', 'images.img_priority', 'products.pop', 'products.color_label', 'products.ai_complete')
->orderBy('img_priority', 'DESC')
->get();
Please try below code.
$products = Product::join('brands','products.brand_id','=','brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images', function($join)) {
$join->on('products.product_id','=','images.product_id')
->where(function($query){
$query->where('img_priority','=','1')
->orWhere('img_priority', '=', null)
})
}
->where(function($query) {
$query->where('products.hide_product', '=', 'N')
->where('products.group_id', '=', $groupID)
})
->orderBy('img_priority','DESC')
->get(array('products.en_71','products.astm','images.file_name',
'products.product_id','products.product_name',
'products.collect_part_no', 'brands.brand_name',
'categories.cat_name', 'products.status',
'images.file_type','products.pop','products.color_label',
'products.ai_complete')
);

Laravel eloquent chunk method return all the time false or null

I am using Laravel v4.2. I want to delete conversation between two users but Now I want that If one user delete the conversation than other user can view the conversation until second user also delete the conversation.
For this I have two column to delete conversation name "delete_on" and "delete_two". For this purpose I am using eloquent chunk method which always return false or null.
$return = Message::where('message_to', '=', $userData['id'])
->where('message_from', '=', $userData['message_from'])
->orwhere(function($query) use($userData) {
$query->where('message_to', '=', $userData['message_from'])
->where('message_from', '=', $userData['id']);
})->chunk(100,function($messages) use($userData){
foreach ($messages as $msg){
if(empty($msg->delete_one)){
$msg->delete_one = $userData['id'];
}else{
$msg->delete_two = $userData['id'];
}
if($msg->save()){
}
}
});
To know more about chunk() refer to this answer mentioned in the comments Thanks Gokigooooks for the acknowledgement.
The syntax you need to employ is the following for in your case it's eloquent:
Eloquent
For first of all check whether you are getting chunk result here like this:
Message::where('message_to', '=', $userData['id'])
->where('message_from', '=', $userData['message_from'])
->orwhere(function($query) use($userData) {
$query->where('message_to', '=', $userData['message_from'])
->where('message_from', '=', $userData['id']);
})->chunk(100,function($messages) use($userData){
foreach ($messages as $msg){
dd($msg); or print_r($msg);
}
});
Now try this
$return = Message::where('message_to', '=', $userData['id'])
->where('message_from', '=', $userData['message_from'])
->orwhere(function($query) use($userData) {
$query->where('message_to', '=', $userData['message_from'])
->where('message_from', '=', $userData['id']);
})->chunk(100,function($messages) use($userData){
foreach ($messages as $msg){
if(empty($msg->delete_one)){
$msg->delete_one = $userData['id'];
}else{
$msg->delete_two = $userData['id'];
}
$msg->save();
}
});

Laravel query not working properly

I do have simple query working properly but I want it working properly using ORM.
I have the following SQL query:
SELECT career_solutions.*,
users.username,
users.profile_picture
FROM career_solutions
INNER JOIN users
ON users.id = career_solutions.user_id
INNER JOIN privacy_settings
ON privacy_settings.user_id = users.id
WHERE career_solutions.topic_category_id = $categoryid
AND ( ( privacy_settings.career_solutions = 0
AND public = 1 )
OR (( users.id IN (SELECT contacts.contact_id
FROM contacts
WHERE contacts.user_id = $id)
OR users.id = $id )) )
ORDER BY date DESC
LIMIT 5000
I'm passing the query directly to to the select method of the DB Facade like so:
DB::select($aboveQuery); and it's working fine.
I am trying to do same using Laravel Eloquent.
By using the following code I am not getting same result as above. Something is wrong with the below query.
$career_solution = CareerSolution::with('user.role', 'user.privancy_setting', 'category', 'sub_category', 'country');
$career_solution = $career_solution->where(function ($query) {
$query->where('expires_at', '>=', date('Y-m-d'))
->orWhere('expires_at', '=', '0000-00-00');
});
$career_solution = $career_solution->Where(function ($query1) use ($id) {
$query1->Where(function ($query2) use ($id) {
$query2->whereHas('user.privancy_setting', function ($query3) {
$query3->where('privacy_settings.career_solutions', '=', 0);
})->where('public', '=', 1);
})->orWhere(function ($query4) use ($id) {
$query4->whereHas('user.contact', function ($query5) use ($id) {
$query5->where('contacts.user_id', '=', $id);
})->orWhere('user_id', '=', $id);
});
});
It is not showing same result as above, let me know how I make it same as above.
The where condition are not used correctly, could you try this:
$career_solution = CareerSolution::with('user.role', 'user.privancy_setting', 'category', 'sub_category', 'country');
$career_solution = $career_solution->where(function ($query) {
$query->where('expires_at', '>=', date('Y-m-d'))
->orWhere('expires_at', '=', '0000-00-00');
});
$career_solution = $career_solution->where(function ($query1) use ($id) {
$query1->where(function ($query2) use ($id) {
// assuming that the relation name in User model is name public function privacy_setting ..
$query2->whereHas('user.privacy_setting', function ($query3) {
$query3->where('career_solutions', '=', 0); // You don't need to specify the table here only the table field you want
})->where('public', '=', 1);
})->orWhere(function ($query4) use ($id) {
// idem here the relation must be name contact
$query4->whereHas('user.contact', function ($query5) use ($id) {
$query5->where('user_id', '=', $id); // idem here
})->orWhere('user_id', '=', $id);
});
});

How to handle And Where and Or Where conditions in Lumen?

I have this query:
SELECT * FROM users
WHERE
gender = "$gender" AND country = "$country"
AND ((city = "$city" AND status = "1")
OR (status IN(2,3)))";
How can I write above query in Lumen ?
What I have tried so far is :
$users = User::where('country', '=', $country)
->where('gender', '=', $gender)
->where(function ($users) {
$users->where('city', '=', '$city')
->where('status', '=', "1");
})
->whereIn('status', [2, 3])
->first();
But this query doesn't returns the expected result.
Any idea what is the fault in my query?
Try the following code.
$users = User::where('country', '=', $country)
->where('gender', '=', $gender)
->where(function ($query) use ($city) {
$query->where(function($query) use ($city) {
$query->where('city', '=', '$city')
->where('status', '=', "1");
})->orWhereIn('status', [2, 3]);
})->first();

Laravel Eloquent search two optional fields

I'm trying to search two optional tables using eloquent:
$users = User::where('ProfileType', '=', 2)
->where(function($query) {
$query->where('BandName', 'LIKE', "%$artist%");
$query->or_where('Genre', 'LIKE', "%$genre%");
})->get();
This works fine for return all results when a user does an empty search, but I am not sure how to adjust this for to search for bandname when that is present and vise versa.
Just to explain what happens on answer below:
Eloquent does a tricky thing here: When you call User::where(...) it returns a Database\ Query object. This is basically the same thing as DB::table('users')->where(...), a chainable object for constructing SQL queries.
So having:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
$query->where(function($query) {
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where_nested('BandName', 'LIKE', "%$artist%", 'OR');
}
// And another
if ($genre = Input::get('genre')) {
$query->where_nested('Genre', 'LIKE', "%$genre%", 'OR');
}
});
// Executes the query and fetches it's results
$users = $query->get();
Building on Vinicius' answer here's what worked:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where('BandName', 'LIKE', "%$artist%");
// Temp Usernamesearch
$query->or_where('NickName', 'LIKE', "%$artist%");
}
// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
$func = ($artist) ? 'or_where' : 'where';
$query->$func('Genre', 'LIKE', "%$genre%");
}
// Executes the query and fetches it's results
$users = $query->get();
Turns out that the second optional field must use or_where only if $artist is not set.
Thanks for your help
I think this is what youre after. Your view would have a form to search artist/genre one or the other can be set, or both, or none.
$users = User::where('ProfileType', '=', 2);
if (Input::has('artist')) {
$users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%');
}
if (Input::has('genre')) {
$users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%');
}
$users = $users->get();
$query = FormEntry::with('form')->where('domain_id', $id);
$query->where(function($query) use ($search, $start, $limit, $order, $dir) {
$query->where('first_name', 'LIKE', "%{$search}%")
->orWhere('last_name', 'LIKE', "%{$search}%")
->orWhere('email', 'LIKE', "%{$search}%")
->offset($start)
->limit($limit)
->orderBy($order, $dir);
});
$entries = $query->get();
$totalFiltered = $query->count();

Categories