How to add object to existing Laravel Query? - laravel

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;
})
);

Related

how to use some eloquent method and then one time use get() and one time use paginate()

I want to use this
$user = User::where('name','john');
then first time
$all = $user->get();
second time
$paginate = $user->paginate(10)
I know I can do like this :
$user = User::where('name','john')->get();
$user2 = User::where('name','john')->paginate(10);
but I want only one time call
User::where('name','john')
what should I do ?
Store the query as a variable and then use it to populate two sets of results.
$query = User::where('name', 'john');
$users = $query->get();
$paginatedUsers = $query->paginate();

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.

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

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;
});

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

Laravel 5 eloquent conditional chaining query

Need help on this simple code, what code should I replace at
$users = User::all(); so I can conditional chaining the scope method and paginate it at the end?
I tried initiate the User object with $users = new User(); and there is error, Trying to get property of non-object error when using at VIEW.
public function index()
{
// user search
$name = $this->request->name;
$email = $this->request->email;
$users = User::all();
if (!empty($name)) {
$users->name($name);
}
if (!empty($email)) {
$users->email($email);
}
$users->paginate(5);
return view('admin.users.index',compact('users'));
}
Thanks in advance
$users = DB::table('users');
$users = empty($email) ? $users->paginate(5) : $users->whereEmail($email)->paginate(5);
You do not need to check for a name if all users have an email, because email is always unique. That way to do the task is faster and more convinient.
In case, if you need to check name or anything else, you can use this:
$users = DB::table('users');
$users = empty($email) ? $users : $users->whereEmail($email);
$users = empty($name) ? $users : $users->whereName($name);
$users = $users->paginate(5);
Try this:
$users = new User;
if( !empty($name) )
$users->whereName($name);
if( !empty($email) )
$users->whereEmail($email);
$users =$users->paginate(5);
I found the answer from the following link
https://stackoverflow.com/a/21739314/417899
Eg code:
$users = new User;
if (!empty($name)) {
$users = $users->name($name);
}
$users = $users ->paginate(5);

Resources