How to remove item from laravel query result and get it? - laravel

In Laravel project I am making a database query
$addresses = DB::table('residences')->where('user_id', '=', Auth::user()->id)->get();
I want to get one address from that query result, if it exists, where 'id' field equals to 10 for example. But I want to remove that address from $addresses query result simultaneously. Is there a simple way to do that?

You can use the reject() method on the $addresses collection, i.e:
$my_result = false;
$addresses = $addresses->reject(function ($value, $key) use (&$my_result) {
if($value->id == 10){
$my_result = $value;
return true
}
return false;
});

Related

How to add object to existing Laravel Query?

What I want to do is add an object to the existing query.
This is my work in progress right now:
$users = ModelUser::where('date_created', $date)->get();
foreach($users as $user){
$obj = ['test1'=> 'val1','test2' => 'val2','test3'=> 'val3',];
$users['items'] = $obj;
}
return $users;
what I'm hoping is a result is like this.
{"username":'Username1', "Fname":'fname1', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username2', "Fname":'fname2', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username3', "Fname":'fname3', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username4', "Fname":'fname4', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
}
Where the items are like in a sub object.
Convert it into a collection and push into it
https://laravel.com/docs/9.x/collections#method-push
Just to understand a bit more, does the "items" element you want to add to the user object have any relationship at the database level?
If so, it would be better to define a relationship within the ModelUser https://laravel.com/docs/9.x/eloquent-relationships#defining-relationships
In case not, I see you're using a $user as an array, but actually $user is a ModelUser element.
So a trick, definitely not recommended, would be:
$user->items = $obj;
You can use laravel map as
$users = ModelUser::where('date_created', $date)->get();
will return a collection. So your expected code will be something like the following
$users = $users
->map(function ($user) use ($obj) {
return $user->items = $obj;
})
);

laravel more than one result from single query

I am trying to get all rows and distinct column from single query. but paginate method is only giving result but not pagination option like total prev next etc..
$offers = Offer::whereHas('users', function ($q) use ($authUser) {
$q->where('user_id', $authUser->parent_id);
$q->where('publisher_id', '=', $authUser->id);
});
and distinct column
$websites = $offers->distinct()->get(['website']);
with pivot columns (just wanted to show my full query)
$offers->orderBy($sortBy, $orderBy)->paginate($perPage)->map(function ($offer) {
if (!empty($offer->users)) {
$manager = $publisher = '';
foreach ($offer->users as $user) {
$manager = $user->pivot->user_id;
$publisher = $user->pivot->publisher_id;
}
$offer->manager = $manager;
$offer->publisher = $publisher;
}
return $offer;
});
Return
return response()->json([
'offers' => $offers,
'websites' => $websites
], 200);
hope my question will make sense.
Thanks.
You should run getCollection() before mapping to get the paginator's underlying collection.
(https://laravel.com/api/7.x/Illuminate/Pagination/LengthAwarePaginator.html#method_getCollection)
$offers->orderBy($sortBy, $orderBy)->paginate($perPage)
->getCollection()
->map(function ($offer) {
// ...
return $offer;
});
I'm answering based on it being $offers:
Your usage of map() is copying the modified results of your paginate() call to a new collection and that collection does not include the pagination information. That's why you no longer have pagination information.
Since there result of paginate() is already a usable collection, you can use each() instead of map() which will alter the objects in-place.

Laravel - Filter out 'null' values from request

I am attempting to filter my $request to not include any input data where the qty field is null (qty sits on a pivot table)
I have already attempted:
$qty = $request->input('qty'); //define qty
$filtered = $request->filter(function ($qty, $key) {
return $qty != null;
});
$filtered->all();
but I receive the error Method Illuminate\Http\Request::filter does not exist, which is strange because I have use Illuminate\Http\Request; in the Controller.
Although I have never filtered data before so I don't know if this is even the correct approach.
I'm pretty positive the $request instance doesn't have a filter method. I think you can achieve what you want using the collect helper:
$input = collect(request()->all())->filter(function($value) {
return null !== $value;
})->toArray();
Update: As of Laravel 8.62.0 the collect method exists on the request:
$input = request()->collect()->filter(function($value) {
return null !== $value;
})->toArray();

Pagination not working on multiple querying

I have a multiple query, but for some reason the pagination is not working, i dont no if the ussue is the way i construct it.
My code:
$query = \DB::table('products');
if ($request->has('type') && $type) {
$query->where('product_type_id', $type);
}
if ($request->has('material') && $material) {
$query->join("product_attribute_materials","products.id","=","product_attribute_materials.product_id")
->whereIn("product_attribute_materials.product_material_id", $material);
}
if($request->has('businessarea') && $area){
$query->join("product_attribute_businessareas","products.id","=","product_attribute_businessareas.product_id")
->whereIn("product_attribute_businessareas.product_businessarea_id", $area);
}
$products = $query->paginate(15);
You need to append the query string to the pagination using append() on $products
Passing array with the keys that you want to pass the query string, will return its value on the next request.
To confirm this, chick the href value from your browser before clicking on page number 2.
$products = $query->paginate(15)->appends(['type', 'material', 'businessarea']);

laravel 5.2 if else to query database

stuck on a form that allows the user to enter a value into a choice of two fields. I can query the database using one field but want to add more range to database queries. With the following code below when i try to access the page to query it just shows me a white screen.
public function index()
{
$data = $request->all();
if(!empty($data['pstoreNum']))
{
$pstoreNum = $data['pstoreNum'];
$result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
}
else if(!empty($data['pweekNum']))
{
$pweekNum = $data['pweekNum'];
$result = DB::table('perfumes')->where('WeekNumber','=',$pweekNum)
->get();
return view('perfumes',compact('result'));
}
}
My routes file simple calls the index function. Any help would be appreciated.
You can add query functions within your query like so
public function index(Request $request)
{
$data = $request->all();
$result = \DB::table('perfumes')->where(function($query) use ($data) {
if(!empty($data['pstoreNum'])) {
$query->where('StoreNumber', '=', $data['pstoreNum']);
}
if(!empty($data['pweekNum'])) {
$query->where('WeekNumber', '=', $data['pweekNum']);
}
})->get();
return view('perfumes',compact('result'));
}
You can then use the one query and add multiple wheres on various conditions.
https://laravel.com/docs/5.2/queries#advanced-where-clauses

Resources