DEV Community

Discussion on: How to Optimize Database Queries in Laravel?

Collapse
 
xorock profile image
xorock

What's the best (fastest) method to add the same value to entire collection? Something like
$date=now();
$posts = Post::get();//[['title'=>'x'], ['title'=>'y']]
And now after merge
[['title'=>'x', 'date' => '2021...'], ['title'=>'y',, 'date' => '2021...']]

Collapse
 
readymadecode profile image
Chetan Rohilla

You can use
$posts = Post::where('date','<',now())->whereIn('title',['x','y'])->get();
the condition on date can be < or > or <= or >=

Collapse
 
xorock profile image
xorock

I don't want to filter results. I want to add one column (like id from external query) to all results. I can do:
Post::get()->map(function($item) use ($now) {
return $item->toArray() + ['date' => $now];
});
But, is there a better solution?

Thread Thread
 
readymadecode profile image
Chetan Rohilla

Try this

$posts = Post::all()->map(function ($post) use($custom_value) {
// modify eloquent object here
$post->custom_column = $custom_value;
//apply any condition if available
return $post;
});