Multiple LIKE clauses in Laravel Eloquent - sql

I currently have this code in my controller:
$JobSuggestions = DB::table('jobs')
->orwhere('skillsetNeeded','like','%Accounting%')
->orwhere('skillsetNeeded','like','%Web Design%')->get();
The above code works, but what I want is to get "Accounting" and "Web Design" from an array, and just loop through that array so that the query is dynamic instead of hard coded on the controller

Try this :
$array = ['web design', 'accounting'];
$result = DB::table('jobs')
->where(function ($query) use($array) {
foreach($array as $key) {
$query->orWhere('skillsetNeeded', 'LIKE', "%$key%")
}
})
->get();

Related

Laravel query with multiple 'with' statements

I'm not sure if there's a a way of doing this but I would like to add a where clause to the second with in my query but it doesn't work. It just returns all the votes as if the condition wasn't there. Any help would be appreciated.
public function PostId($request)
{
$post_id = $request->post_id;
$user_id = auth('api')->user();
$post = Post::with('categories')
->where('id', $post_id)
->with('votes')
->where('user_id', $user_id->id)
->first();
return $post;
}
You need to use closure in your with statement.
Also, I'd recommend using findOrFail() instead of where conditional for your query. Therefore, in case you pass a wrong post_id in your request an exception 404 will be thrown.
A nicer way to accomplish what you want could be:
public function PostId($request)
{
$post = Post::with(['categories', 'votes' => function($query){
$query->where('user_id', auth('api')->user()->id);
})
->findOrFail($request->post_id);
return $post;
}
$post = Post::find($post_id) // Find method will return only first record. no need to call ->first() explicitly.
->with([
'categories',
'votes'
])
For the ->where('user_id', $user_id->id), you dont need to do it in here as you already have defined the relation 'votes'.
Class Post
{
public function votes()
{
return $this->hasMany(Vote::class)->where('user_id', $this->user_id); // You can have the where condition here assuming you have user id field present in the Post model. Else you can keep it as below in your query
}
}
With user id in the runtime query
$post = Post::find($post_id)
->with([
'categories',
'votes' => function($query) use($user_id) {
$query->where('user_id', $user_id->id);
}
])

laravel Show only related data in search filter

I am trying to create a search filter:
if ($request->has('street')) {
$streets->where('name', 'like', '%'.$request->street.'%');
}
if ($request->has('house')) {
$streets->whereHas('properties', function ($query) use ($request) {
$query->where('house_number', $request->house);
});
}
return $streets->get();
This currently gets the street data. I want to do something like this ?street=b-34&house=21 and to display the house data.
At the moment I am only getting the street data.
Your problems seems one every Laravel developer will go through one day. You forgot to return the query to the original constructor.
You have:
$streets->where('name', 'like', '%'. request('street') .'%');
when you should have:
$streets = $streets->where('name', 'like', '%'. request('street') .'%');
You are chaining the methods so you should have it return the original query constructor
EDIT Based on comments:
Besides from not returning the query as I stated above you are using whereHas as #thisiskelvin have pointed out in his answer.
You should be using
if (request()->has('street')) {
$streets = $streets->where('name', 'like', '%'. request('street') .'%');
}
if (request()->has('house')) {
$streets = $streets->with(['properties' => function ($query) {
$query->where('house_number', request('house'));
}]);
}
return $streets->get();
You should be able to achieve this by using the ->with() eloquent method. If the request has a house query, it will return all properties where the house_number equals the queried house number. Once found will attach to the returned results:
if (request()->has('street')) {
$streets = $streets->where('name', 'like', '%'. request('street') .'%');
}
if (request()->has('house')) {
$streets = $streets->with(['properties' => function ($query) {
$query->where('house_number', request('house'));
}]);
}
return $streets->get();
Note: I have changed $request to use the request() helper.

Laravel query - request for a phrase to the translation table

I have a problem with finding results. I search the 'name' records in the translation table for the occurrence of any of the words.
//Bad result:
return Product::whereIn('id', $ids)->whereHas('translations', function ($query) use ($findTextWildcards) {
foreach ($findTextWildcards as $value) {
$query->orWhere('name', 'like', "%{$value}%");
}
});
//good result but difficult query
return Product::whereIn('id', $ids)->where(function ($query) use ($findTextWildcards) {
foreach ($findTextWildcards as $value) {
$query->whereHas('translations', function ($q) use ($value){
$q->where('name', 'like', "%{$value}%");
});
}
});
Try with this one. Probably the problem was that you didn't wrap this with additional where closure.
return Product::whereIn('id', $ids)
->whereHas('translations', function ($query) use ($findTextWildcards) {
$query->where(function($query) use ($findTextWildCards) {
foreach ($findTextWildcards as $value) {
$query->orWhere('name', 'like', "%{$value}%");
}
});
});

Eloquent filtering with multiple parameters

I am writing a search functionality which basically looks up several tables.
The DB structure and relationships are as follows:
`users`
id
name
user_type_id
`user_type`
id
type
`user_nicknames`
id
user_id
nickname
User model has a \Illuminate\Database\Eloquent\Relations\BelongsTo relationship with user_type
and a \Illuminate\Database\Eloquent\Relations\HasMany relationship to user_nicknames
What I am trying to get is search against a specific searchTerm which can be found either in users table and in user_nicknames
This one is failing right now:
$user = $this->user->newQuery();
$user->whereHas('userType', function ($query) use ($filters) {
$query->where('type', $filters['type']);
});
$user->whereHas('userNickName', function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$nickname.'%');
});
Please take note that I'd prefer to use the eloquent relationships for this rather than multiple joins.
Any ideas?
In your User model add these functions:
public function scopeUserTypeFilter($query, $filters)
{
return $query->whereHas('user_type', function ($query) use ($filters) {
$query->where('type', $filters['type']);
});
}
public function scopeNicknameFilter($query, $nickname)
{
return $query->whereHas('user_nick_name', function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$nickname.'%');
});
}
Then you can use these on your controller:
public function search(Request $reqeust)
{
$users = User::where(function ($query) use ($request) {
return $query->when($request->filled('s'), function($query) use ($request) {
return $query->nicknameFilter($request->s);
});
})->where(function ($query) use ($request) {
return $query->when($request->filled('userType'), function($query) use ($request){
return $query->userTypeFilter($request->userType);
});
})->get();
}

Yii2 Sort multiple parameters URL

I have an endpoint in yii2 where I need to sort by multiple parameters. Im using ActiveDataProvider. This is the enpdoint:
public function actionIndex($client)
{
$sort = new Sort([
'attributes'=> ['name','mail','crdate']
]);
$query = Customer::find()
->andWhere(['client' => $client])
->orderBy($sort->orders);
$provider = new ActiveDataProvider(['query' => $query]);
return $provider->getModels();
}
Now sorting by a single parameter as in: customers?client=1&sort=mail works fine.
I want to sort by multiple parameters though. How should I do this in the url?
Set
$sort = new Sort([
'attributes'=> ['name','mail','crdate'],
'enableMultiSort' => true,
]);
Now you can pass multiple sort column by separating them with , like
?sort=name,mail
If you prepend name with - you get descending order otherwise it's ascending.
If you want to change , separator to something else set it in separator configuration key for Sort object.
You should try search model for Costumer model
public function search($params)
{
$query = Costumer::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([some condition for search]);
return $dataProvider;
}