Laravel/Lumen api filter - php

recently I'am trying to make my api filtering work. I need to filter my products like this: http://localhost/search?feature_id=1,2,3,4,5...
Everything is fine if I'm sending only 1 id. But how to make it work in this way?
This is my controller:
public function search2(\Illuminate\Http\Request $request) {
$query = DB::table('tlt_product_features');
if ($request->has('feature_id') ) {
$query = $query->whereIn('feature_id', [$request->get('feature_id')]);
}
$products = $query->get();
return response()->json([
'products' =>$products
]);
}

Use explode() to make arrays of id.
$ids = explode(",",$request->get('feature_id'));
$query = $query->whereIn('feature_id', $ids);

To get an array out of the box on the Laravel / Lumen side, you have to send the array this way :
http://localhost/search?feature_id[]=1&feature_id[]=2&feature_id[]=3...
In a weak typed languages like PHP, the [] is actually being used as an internal work around in order to be able to get multi valued parameters. You could also specify an index :
http://localhost/search?feature_id[0]=1&feature_id[1]=2&feature_id[2]=3...
You could then use in you controller :
if ($request->filled('feature_id')) {
// You could also check that you have a php array : && is_array($request->input('feature_id'))
// And that it's not an empty array : && count($request->input('feature_id'))
$query = $query->whereIn('feature_id', $request->input('feature_id'));
}

Related

WhereIn Inside ->where() array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.

Laravel - Paginate function doesn't working on query building using IF

I am using paginate() on my Controller to pass data to the View. This is my index function using the paginate()
$userData = User::with('jobUnit')
->select('nip','name','address','phone','email','unit_id')
->paginate(10);
return view('users.index', [
'users' => $userData
]);
This is the result:
In the other function, I needed to add some IF conditions on the queries that is look like this:
$keyword = $request->keyword;
$searchedData = User::with('jobUnit')->select('nip','name','address','phone','email','unit_id');
if ($request->searchFilter == 'nip') {
$searchedData->where('nip','like','%'.$keyword.'%');
}
$searchedData->paginate(10);
The results is different, which is a problem for me because I am using the pagination links in the View. Here is the results:
Does the pagination() not working? Because I tried using the get() as well which should returns "Collection", but it was still returning the "Builder" results.
you need another variable to store the return data
$searchDataPaginated = $searchedData->paginate(10);
or using the current one if you want
$searchedData = $searchedData->paginate(10);

how can get a specific value from database in using php laravel model

function subscriptionpack(Request $request)
{
$sub = subscription::all();
$details = $sub['details'];
dump('$details');
}
I can get all values from this code, but I can't get the specific field that named details. When I call dump($sub) it was shown all details, but the dump('$details') make an error that is undefined index:details
anyone can help me to correct this code?
You can use select method to select specific column data :
$sub = subscription::select('details')->get();
Or, you can do with on get() method as like :
$sub = subscription::get(['details']);
If you need single column from the result set use pluck
$subs = subscription::all();
$details = $subs->pluck('details')->toArray();
You can either loop over to your collection e.g
foreach($sub as $s){
dump($s->details)
}
or you can try something like.
$sub->first()->details
but this will give you only first details element from your collection.
First a model should be in singular, no spacing between words, and capitalised.
You should use Subscription::all(); not subscription::all();. You should read Laravel conventions
use App\Subscription;
..
function subscriptionpack(Request $request)
{
$sub = Subscription::all()->pluck('details');
dd($sub);
}

Passing a parameter to a custom find method in cakephp 3.x

I want to build a custom find function that retrieves bands for a given genre, i have tried this but the function can't access to the parameter $genre:
public function findGenre(Query $query, array $options)
{
$genre = $options['genre'];
$bands = $this->find()->contain([
'Genres' => function($q){
return $q->where(['Genres.id' => $genre]);
}
]);
return $bands;
}
I can access the $genre outside the contain() method, but not inside it.
My question is, how can i pass the $genre var to the function($q) inside the contain method.
I found where the problem is, i had to use the keyword use after the function($q), so that part of the code will look like this
$bands = $this->Bands->find()->contain('Genres', function($q) use ($genre){
return $q->where(['Genres.name'=>$genre]);
});
Also,the contain() method returns all the data even if the bands don't belong to a genre, but when i replaced it with matching() it worked just fine.
I hope this will help anyone who is having a similar problem in the future.
I was facing same issue but now it's resolved. I will explain you step by step:
My tables are:
articles: id,name,status,created
tags:id,name,status,created
articles_tags: id,article_id, tag_id
my query is this:
I want to pass my $tag_data['slug'] in matching variable but
directly this variable is not working in query. So I put in simple
$uses variable and now it's working properly.
$uses = $tag_data['slug'];
$contain_article = ['Tags'];
$query = $this->Articles->find('All')
->where(['Articles.status' => '1'])
->contain($contain_article)
->matching('Tags', function ($q) use ($uses) {
return $q->where(['Tags.slug' => $uses]);
});
Please try this :-)

Ignore "where" clause in Laravel database query if no filter is provided

I'm currently trying to find the cleanest way to go about a query in Laravel 5.1. I'm creating an API that will return a JSON string from a MySQL database.
I would like to be able to have a URL like
mydomain.com/api/courses
which will return a JSON list of all of our courses. And I would also like to be able to pass in a GET query parameter like
mydomain.com/api/courses?subject=BUS
which will return only business courses. Pretty basic so far. In my controller, I have
$subject = \Request::input('subject');
if ($subject) { //filter to only query parameters
$results = \DB::table('course_listings')
->where('subject', $subject)
->get();
} else { //return all results
$results = \DB::table('course_listings')->get();
}
However, it seems a little unnecessarily messy, especially if I want to start adding in additional query parameters. What I would like to do is to be able to just ignore the where() if the query parameter is blank.
$results = \DB::table('course_listings')
->where('subject', $subject) //ignore this line if no $subject
->get();
And for performance purposes, I would also want to avoid having to load all of the results, and then applying the filter afterwards. Is there anything in Laravel built for this?
You can save your query to a variable, and then only apply the where in your if block:
$subject = Request::input('subject');
$query = DB::table('course_listings');
if ($subject) {
$query->where('subject', $subject);
}
$results = $query->get();
If you want to completely forgo the if statement, you can do this:
$constraints = array_only(Request::input(), 'subject');
$results = DB::table('course_listings')->where($constraints)->get();

Categories