search multi column and join another query when a condition is true - laravel

i want to search in posts table for a search query, i should search in title and slug columns, also i have a checkbox to search only published posts.
in my code my query always ignore is_publish query. how can i search on only published post when "search on published post" checkbox is checked?
$query = Post::when($request->target, function ($q) use ($request) {
$q->where('title','LIKE', "%$request->target%")->orWhere('slug', 'like', "%$request->target%");
})->when($request->publish, function ($query) use ($request) {
$query->where('is_publish', 1);
});

You can write like as below:
$query = Post::when($request->target, function ($q) use ($request) {
$q->whereRaw("(title LIKE '%$request->target%' or slug LIKE '%$request->target%')")
})->when($request->publish, function ($query) use ($request) {
$query->where('is_publish', 1);
});

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

Laravel - whereHas query not returning correct records

I am currently writing a search query but I'm having issues joining a where with a whereHas
if I wanna search for categories only..
The below query works if I just search for categories solo
$goals = $myGoals
->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->paginate(10);
if I wanna search for the title only..
Same as above if I wanna search for the title of goals solo
$goals = $myGoals->where('title', 'like', "%$search%" )->paginate(10);
both of the queries work if I want to search for them individually.
Query attempt
Below is the query I've written to allow a user to search for the title of a goal and the name of a category.
$myGoals = $team->goals();
$goals = $myGoals
->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->where('title', 'like', "%$search%" )->paginate(10);
I have tried the above query but the search results return empty when I enter an input. I've also tried swapping the where() to orWhere() which then returns a goal that doesn't belong to the $team model instance but it's a goal record linking to a different Team model id within the pivot table.
Can anyone spot where I am going wrong? thanks
You need to use it all inside where.
$goals = $myGoals->where(function ($query) use ($search){
return $query->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->orWhere('title', 'like', "%$search%" );
})->paginate(10);

Relational Query In laravel

My Code
$videos = ExamVideo::with([
'user' => function ($query) use ($request) {
$query->where('user_name', 'like', '%'.$request->search.'%');
}
])->where('is_marked','=', 0)->get();
return $videos;
I want to get only those videos where is_marked is zero & it's relation user_name match my search result.
But I get all the videos which marked is zero.
The with method is only for eager loading and not used to filter your records.
You can accomplish what you want with the whereHas method which will perform a query on the relation:
$videos = ExamVideo::whereHas('user', function ($query) use ($request) {
$query->where('user_name', 'like', "%{$request->search}%");
})->where('is_marked', false)->get();
For more information about whereHas: https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence

how to Ignore "where clause" if no query is provided with Laravel

I want to get all the leads when the query is empty, but if the 'subService' query is provided then it should fetch all the leads that have the same subService name
I am trying to get sub service name by providing this subService.name in where clause
subService is one many relationship
this is not the full code.
return Lead::with(['subService'])
->where(function ($query) use($subService) {
if ($subService) {
$query->where('subService.name','like', '%'.$subService.'%');
}
})
return Lead::with(['subService'])->when($subservice, function ($query) use ($subservice) {
return $query->whereHas('subService', function ($query) use ($subservice) {
$query->where('name', 'LIKE', "%{$subservice}%");
});
})->get();

Laravel Query Builder relationship plus no relationship

I currently have this which works for querying a relationship:
$users = User::query();
$post_id = $request->input('post_id');
$users->whereHas('posts', function ($query) use ($post_id) {
$query->where('id', $post_id);
});
return $users->get();
But in the results of this query I would also like to include Users that do not have any posts connected to them. So the result becomes: users without posts + users with a specific post (code above). Is this possible?
Use doesntHave():
$users->whereHas('posts', function ($query) use ($post_id) {
$query->where('id', $post_id);
})->orDoesntHave('posts');

Resources