Remove Nulls From Query Builder Laravel - laravel

Im having a little trouble with some return data that I'm getting when running a Query Builder then paginating the data
I was wondering if anyone knew how I could remove Null Results before I paginate the data.
// So Before I hit this
$return = $tld->paginate($request->get('limit'))->toArray();
This is the issue after I paginate
array:12 [
"current_page" => 1
"data" => array:12 [
0 => null
1 => array:3 [
I need to get rid of those Null values, I know how to do it after I paginate however I want to get rid of them before I paginate...
Im hoping that some of you laravel Gods can help me ..
Added this extra logic for $tld
private function newest(Request $request)
{
$this->validate($request, [
'timescale' => [
'required',
Rule::in(['today', 'this_week', 'this_month', 'all_time'])
]
]);
$tld = TimelineItem::where('timeline_items.created_at', '>', $this->timescaleToHours($request->get('timescale')));
if ($request->search_content) {
$tld = $this->searchContent($tld, $request->search_content, 0.4);
} else {
$tld = $tld->orderBy('timeline_items.created_at', 'DESC');
}
if ($request->types) {
$tld = $this->filters($tld, $request->types);
}
if ($request->tags) {
$tld = $this->tags($tld, $request->tags);
}
return $tld;
}

You can use filter() to remove null. Laravel Collection filter()
$response = $tld->paginate($request->get('limit'))->toArray();
$response['data'] = collect($response['data'])->filter()->toArray();
return $response;

Related

Laravel 7 : Why I am Getting Only First Array? I want to Fetch All Category ID data

I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.

Laravel - How to pass variable as parameter to external API using guzzle

I am using Laravel-5.8 and Guzzle to consume an external api:
public function index()
{
try{
$myparam = 'JKK123';
$client = new Client();
$res = $client->request('GET','https://examplet/tracking/$myparam', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
$currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
})->first();
$currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
dd($currentLocationFilter);
return view('index', [
'currentLocation' => $currentLocation,
'currentLocationFilter' => $currentLocationFilter,
'geoLocation' => $geoLocation
]);
}catch (Exception $exception) {
Log::error($exception);
return back();
}
}
I am trying to pass the variable as parameter to the API. I didn't put it directly because it changes. I just tried to test.
When I did this as shown in the code above
$res = $client->request('GET','https://examplet/tracking/$myparam', [ ...
and then
dd($currentLocationFilter);
I got:
array:1 [▼
0 => ""
]
But when I put the value directly,
$res = $client->request('GET','https://examplet/tracking/JKK123', [
I got the required result:
array:2 [▼
0 => "2.1234565432145"
1 => "1.7864321249555"
]
How do I paa the variable as parameter into the external API?
Thanks
Use double quotes for executing variable like this:
$res = $client->request('GET',"https://examplet/tracking/{$myparam}", [...

Laravel Query Builder Issue Remove Null Values

Hi all you smart individuals i'm hitting a solid wall here with someone else code that i'm trying to fix a issue.
The issue is that when this query builder has got all the results there seems to be some coming back with null values and i'm not sure how to remove them before I paginate the data, I know how to do it if it was a collection however maybe some of you might be-able to help me.
so currently the logic goes into this pagination
$return = $tld->paginate($request->get('limit'))->toArray();
$tld being the eloquent builder.
Which then gets sent into this function that was created..
$return = $this->makePagination($return);
public function makePagination($object = [], $filters = []) {
return [
'data' => [
'items' => $object['data'],
'pagination' => [
'from' => $object['from'],
'to' => $object['to'],
'total' => $object['total'],
'per_page' => $object['per_page'],
'first_page' => [
'number' => 1,
'url' => $object['first_page_url']
],
'last_page' => [
'number' => $object['last_page'],
'url' => $object['last_page_url']
],
'next_page' => [
'number' => $object['current_page'] + 1,
'url' => $object['next_page_url']
],
'prev_page' => [
'number' => $object['current_page'] - 1,
'url' => $object['prev_page_url']
]
],
'params' => $filters
]
];
}
But then i'm getting a response like this with Null values and I would like to remove them before any of this pagination happens
{
"data": {
"items": [
{
"id": 13771,
},
null,
{
"id": 4125,
},
Side note if I run $tld->get() I can see all the results and there are null values in there so if anyone can show me how to remove the null values that would be a great help <3 you all if you can help me ...
Update
Ive also tried $tld->get()->filter(); and thats also not removing the null values I still get this response
[
{
"id": 13771,
},
null,
{
"id": 789,
}
]
I think I fixed it with a little hack
$filtered = collect(array_values(array_filter($tld->get()->toArray())));
return $this->paginate($filtered, $request->get('limit') ?? 15 , $page = null, $options = []);
and then created a collection paginator
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
#Bob Hiller Please use whereNotNull in query to remove null entries.
$tld=$query->get();
$tld->filter(function ($value) { return !is_null($value); });
$return = $tld->paginate($request->get('limit'))->toArray();

Using pluck() helper function in laravel

I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar#noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh#noeticitservices.com"
}
]
}
I just want to get the value key form the users array via laravel collection something like this:
$userIds = $request->users->pluck('value');
so that I can put them into query:
$user = User::all()->whereIn('unique_id', $userIds);
May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
I'm still learning collections, any suggestions is appreciated. Thanks
Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.
PS. If you have multiple DB actions in single method, It's good to have DB transaction.
\DB::transaction(function () use ($request) {
// convert it to collection
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
});
// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);
or you'll need something like this:
return \DB::transaction(function () use ($request) {
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
return response()->json([
'message' => 'Created Successfully',
'data' => $team,
], 201);
});
I just want to get the value key form the users array via laravel collection
Just use map then:
$userIds = $request->users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});
Edit:
if $request->users is not a collection, make it one before calling map:
$users = collect($request->users);
$userIds = $users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});

How to use random_score in yii2 elastic search when working with dataprovider

How can i add random_score in dataprovider search query?
I am using yii2-elastic search extension.
https://github.com/yiisoft/yii2-elasticsearch
First of all you have to set all fields in attributes() including the random_score field.
And then Try this way.
$UserDetail = User::find();
if($this->search != '')
{
$query = $UserDetail->query($condition);
}
else
{
$query = $UserDetail;
}
$provider = new ActiveDataProvider([ 'query' => $UserDetail, 'pagination' => [ 'pageSize' => 10, ] ]);
return $provider;

Resources