laravel eloquent multiple where statement - laravel

I have used the following code for conditional where query. But I didnt get the result in foreach statement but if I use $member->first() I am getting the result. Is this the correct way to use conditional where in laravel?
$member = Member:query();
if(!empty($param['activity'])){
$member->where('activity', 'LIKE', $param['activity'] .'%');
}
if(!empty($param['MemberName'])){
$member->where('MemberName', 'LIKE', $param['MemberName'] .'%');
}
if(!empty($param['Designation'])){
$member->where('Designation', 'LIKE', $param['Designation'] .'%');
}
$member->take(100)->skip($offset)->get();
foreach ($member as $arr)
{
....
}

This is totally the right way to do it. However you're missing one little thing. get() will return the result but the $member will still be the query builder instance. What you need to do is assign the result to $member
$member = $member->take(100)->skip($offset)->get();

Related

how to use whereHas in laravel

I am new to laravel,
I need to create a query for the db,
$query = Deal::query();
I want to use the wherehas operator.
this is my code that is worked.
else if ($group_by == 'precedence') {
if($get_deals_for == 'noprecedence'){
$get_deals_for = 0;
}
$precedenceStatus = $get_deals_for;
$query-> where('precedence', '=', $precedenceStatus);
// \Log::info('The request precedence: '.$precedenceStatus);
}
I want to add this code also to the query
if($person) {
$query->whereHas('personnel', function ($subQuery) use ($person) {
$subQuery->where('id', '=', $person);
});
}
So I need to change the first code?
how I can convert the first code to wherehas?
the first code is from table called deal, the second section is from realtionship called personnel.
the second section worked in other places in the code, I just need to fix the first section and not understand what to write in the use
I try this and get error on the last }
else if ($group_by == 'precedence') {
if($get_deals_for == 'noprecedence'){
$get_deals_for = 0;
}
$precedenceStatus = $get_deals_for;
$query-> where('precedence', '=', $precedenceStatus)
-> when ($person, function($query) use($person) {
$query->whereHas('personnel', function ($query) use ($person) {
$query->where('id', '=', $person);
});
})
}
There is a method you can use called when(, so that you can have cleaner code. The first parameter if true will execute your conditional statement.
https://laravel.com/docs/9.x/queries#conditional-clauses
$result = $query
->where('precedence', '=', $precedenceStatus)
->when($person, function ($query) use ($person) {
$query->whereHas('personnel', fn ($q) => $q->where('id', '=', $person));
})
->get();
You should also be able to clean up your precedence code prior to that using when( to make the entire thing a bit cleaner.
Querying to DB is so easy in laravel you just need to what you want what query you want execute after that you just have to replace it with laravel helpers.Or you can write the raw query if you cant understand which function to use.
using,DB::raw('write your sql query').
Now Most of the time whereHad is used to filter the data of the particular model.
Prefer this link,[Laravel official doc for queries][1] like if you have 1 to m relation ship so u can retrive many object from one part or one part from many object.like i want to filter many comments done by a user,then i will right like this.
$comments = Comment::whereHas('user', function (Builder $query) {
$query->where('content', 'like', 'title%');
})->get();
$comments = Here will be the model which you want to retrive::whereHas('relationship name', function (Builder $query) {
$query->where('content', 'like', 'title%');
})->get();
you can also write whereHas inside whereHas.
[1]: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

use like on laravel can't display date search

i want to search data based nama_kegiatan or tanggal_kegiatan where these two name form my table field, this code from my controller :
public function search(Request $request){
$cari = $request->search;
$caritanggal = date($request->datekeg);
$infokeg = Infokeg::where(function ($query) use ($cari) {
$query->where('nama_kegiatan','like',"%$cari%")->get();
})->orWhere(function($query) use ($caritanggal) {
$query->where('tanggal_kegiatan', $caritanggal)->get();;
})->paginate(10);
return view('infokeg/infokeg', ['infokeg' => $infokeg]);
}
when i am using like on nama_kegiatan, tanggal_kegiatan didnt work and just display all data, but when i delete like from nama_kegiatan, its work, but i cant search nama_kegiatan using like, so how to solve it ?
Maybe you can try to get() all the result after the query? Somethings like
$infokeg = Infokeg::where('name_kegiatan','LIKE','%'.$cari.'%')->orWhere('tanggal_kegiatan',$caritanggal)->get();
IMO the get() and paginate() cannot be use at the same time if I have not get it wrong. If you need to paginate after all the result, you can do create Paginator manually. Maybe this link can help you. Hope this will help you and please correct me if anything wrong. Thanks!
If you want to see what is run in the database use dd(DB::getQueryLog()) after query to see what queries exactly were run.
$infokeg = Infokeg::where('nama_kegiatan','like', "%" . $cari ."%")
->orWhere(function($query) use ($caritanggal) {
$query->where('tanggal_kegiatan', $caritanggal);
})->paginate(10);
just make it into if condition
public function search(Request $request)
{
$cari = $request->search;
$caritanggal = $request->datekeg;
if (isset($cari)) {
$infokeg = Infokeg::where('nama_kegiatan', 'like', '%'.$cari.'%')
->paginate(5);
}elseif (isset($caritanggal)) {
$infokeg = Infokeg::where('tanggal_kegiatan', 'like', '%'.$caritanggal.'%')
->paginate(5);
}elseif (isset($cari)&&isset($caritanggal)) {
$infokeg = Infokeg::where('nama_kegiatan', 'like', '%'.$cari.'%')
->orWhere('tanggal_kegiatan', 'like', '%'.$caritanggal.'%')
->paginate(5);
}
return view('/admin/infokeg/infokeg', ['infokeg' => $infokeg]);
}

Laravel break up paginated eloquent query

I currently have:
$comments = $this->post->comments()
->where('comment', 'like', "%{$search}%")
->paginate(50);
But I'd like to do something like the below, as I have multiple filters that I'm going to apply:
$comments = $this->post->comments();
if(condition)
{
$comments->where('comment', 'like', "%{$search}%");
}
$comments->paginate();
But the code above doesn't work as I then get errors on things like $comments->links() for pagination links in the view, indicating that this doesn't work.
What you can try is something like this, I don't know what Laravel version you are using, also I don't know the structure you have of your models, but here's the documentation about this example:
$conditions = 1;
$comments = Post::with('comments')
->whereHas('comments', function ($query) use ($conditions){
// pass your conditions
if(!$conditions){
$query->where('comment', 'like', "%%")
}
// more conditions, etc
$query->where('comment_id', 'like', '%%');
})->paginate(50);
It was missing $comment = in front of the query clauses:
$comments = $this->post->comments();
if(condition)
{
$comments = $comments->where('comment', 'like', "%{$search}%");
}
$comments = $comments->paginate();

or where clause - Laravel eloquent

I have this query:
if($keyword){
array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}
The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).
I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.
For the example:
if($fromPrice){
array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
array_push($where, ['price', '<=', $toPrice]);
}
And the query is:
$cars= Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where)->paginate(10);
I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.
Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?
to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:
$query = Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where);
if($keyword){
$query = $query->where(function ($query) use ($keyword) {
$query->where('name_fr', 'like', $keyword)
->orWhere('name_en', 'like', $keyword);
});
}
$cars = $query->paginate(10);
You can also go with
$propertyQuery = Property::query();
if($keyword){
$propertyQuery->where(function($query) use ($keyword){
$query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
});
}
$cars = $propertyQuery->paginate(10);

Laravel 4 - Eloquent 'where' only if exists

I'm working in a search engine, and I have something like this in my Controller:
$user = User::where('description', 'LIKE', '%'.$keyword.'%')
->where('position', $position)
->where('age', $age)
->orderBy('created_at', 'DES')
->paginate(10);
What I want is to use the $position and $age filters only if they exist. I mean, if I only set the keyword, I expect the application to show me all the users with this keyword (whatever its position and age are).
I know a way to do it... using if($position == '')... else..., but I would like to do (if possible) in my Eloquent consult. Something like... ->where('position' ? $position).
Any idea how to do it in the simplest way?
Thanks in advance!
Using if conditions would be the best way to do this. As far as I know the functionality your after isn't built into Eloquent.
I would do it using conditionals like so:
$query = User::where('description', 'LIKE', '%'.$keyword.'%');
if($position) {
$query->where('position', $position);
}
if($age) {
$query->where('age', $age);
}
$user = $query->orderBy('created_at', 'DES')->paginate(10);
If you want to keep your controller clean and avoid if - else you can create some scopes in your model.
For exemple :
public function scopePosition($query, $position)
{
//If $position in empty, return the query without where clause
return !($position == '') ? $query->where('position', $position) : $query;
}
And :
public function scopeAge($query, $age)
{
//If $age in empty, return the query without where clause
return !($age== '') ? $query->where('age', $age) : $query;
}
And then use it like this:
$user = User::where('description', 'LIKE', '%'.$keyword.'%')
->position($position)
->age($age)
->orderBy('created_at', 'DES')
->paginate(10);
More abour query scope:
http://laravel.com/docs/eloquent#query-scopes

Resources