How to get all between two dates by carbon - laravel

I get two date from user for example :
2016-10-01
2016-11-05
now I would like to get all dates between these two dates :
2016-10-01
2016-10-02
2016-10-03
2016-10-04
...
2016-11-05
I think I must use the carbon library. but I don't know how can I do !

Try this:
$from = Carbon::parse('2016-10-01');
$to = Carbon::parse('2016-11-05');
With Carbon
$dates = [];
for($d = $from; $d->lte($to); $d->addDay()) {
$dates[] = $d->format('Y-m-d');
}
return $dates;

Related

Laravel MongoDb WhereMonth/WhereYear return empty

I m trying to filter my document on created_at with whereMonth/whereYear clauses. But it always returns empty collection. I can't understand why.
Example :
$collection = MyModel::whereMonth('created_at', '06')->get();
I tried to change type of parameter with '6' or (int) 6... but nothing changed.
Someone to explain me why it doesn't work as documentation says (jenssegers package or laravel).
I didn't found any solution...
Thank you.
Ok i found solution. I made my query in a whereRaw and used this :
$month = (int) $request->month;
$queryMonth = [
'$expr' => [
'$eq' => [['$month' => '$created_at'], $month],
]];
$collection = Model::whereRaw($queryMonth)->get();
Same for requesting "year".
Thanks for all.
$collection = MyModel::all();
foreach($collection as $result)
{
$datetime = $result->created_at;
$date = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $datetime);
$month = $date->month;
if($month == '06')
{
$collection = MyModel::whereMonth('created_at', $month)->get();
}
}

Laravel Eloquent : Get records according to day and month

I'm trying to get records whose birthday is today, today + 1, today + 2.
Suppose someone is born on 16-05-1991.
I've to find those records whose birthday is today, tomorrow, and day after tomorrow
$todayDate = date('Y-m-d');
$toDate1 = date('Y-m-d', strtotime($todayDate . ' + 1 days'));
$toDate2 = date('Y-m-d', strtotime($todayDate . ' + 2 days'));
I tried to use orWhereDay, orWhereMonth but it doesn't make sense.
Edit : I've done like this but I'm looking for a more efficient way to do this.
https://pastebin.com/GRdRH2jC
The correct code seems to be
$date = new DateTime;
$date2 = $date->modify('+1 day');
$date3 = $date->modify('+2 day');
$formatted_date = $date->format('Y-m-d H:i:s');
$formatted_date2 = $date2->format('Y-m-d H:i:s');
$formatted_date3 = $date3->format('Y-m-d H:i:s');
Tinker output
>>> $date = new DateTime;
=> DateTime #1558028326 {#3144
date: 2019-05-16 17:38:46.169709 UTC (+00:00),
}
>>> $date2 = $date->modify('+1 day');
=> DateTime #1558114726 {#3144
date: 2019-05-17 17:38:46.169709 UTC (+00:00),
}
>>> $date3 = $date->modify('+2 day');
=> DateTime #1558287526 {#3144
date: 2019-05-19 17:38:46.169709 UTC (+00:00),
}
>>> $formatted_date = $date->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>> $formatted_date2 = $date2->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>> $formatted_date3 = $date3->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>>
Using Carbon
>>> $today = Carbon\Carbon::now()
=> Carbon\Carbon #1558072952 {#3119
date: 2019-05-17 06:02:32.343195 UTC (+00:00),
}
>>> $date2 = $today->addDay();
=> Carbon\Carbon #1558159352 {#3119
date: 2019-05-18 06:02:32.343195 UTC (+00:00),
}
>>> $date3 = $today->addDays(2);
=> Carbon\Carbon #1558332152 {#3119
date: 2019-05-20 06:02:32.343195 UTC (+00:00),
}
>>>
You can use Carbon. Example:
User::whereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(1)]);
If you want to use or, you will need to group them like so:
User::where(function($query) {
$query->whereDate('birthday', Carbon::today())
->orWhereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(1)])
->orWhereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(2)])
})->get();
You can use Carbon class for time, makes things a bit easier
Use Carbon/Carbon
$today = Carbon::now()->today();
$toDate1 = Carbon::now()->today()->addDays(1);
$todate2 = Carbon::now()->today()->addDays(2);
$todate2 = Carbon::now()->today()->addDays(3);
where('birthday, '>', $today)->where('birthday', '<', $toDate1); //today
where('birthday, '>', $toDate1)->where('birthday', '<', $toDate2); //today + 1
where('birthday, '>', $toDate2)->where('birthday', '<', $toDate3); //today + 2
if you just want month and day then you can do it like this
$today = Carbon::now()->today()->format('m-d');
$upcomingBdays = model::select('id', ... , 'birthday')->get()->filter(function ($model) {
// get the bday and change the year to this year so we can simply compare dates
$bday = Carbon::parse($model->birthday)->year(today()->year); // you can skip parsing if you have the field in the protected $dates on model
return $bday->between(today(), today()->addDays(2));
});
Without any more information about the model you are querying, this should get you what you want.
Make sure you also have the birthday field for the model added to the
protected $dates []; array on the model itself so it automatically get's parsed by Carbon.

Getting nothing when doing whereBetween in laravel

I'm trying to create a sort function where if it's selected it will display the necessary amount of orders. For example if the user selects to display orders from the last 3 months then that needs to be displayed.
The problem I'm having is that nothing is being shown when I dd($three_months)
public function trackOrders()
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$orders = Auth::user()->orders->sortByDesc('order_date');
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
$from = Carbon::now('+2:00');
$to = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
dd($three_months);
return view('public.users.track-orders', compact('menus_child', 'contacts', 'orders', 'order_item'));
}
but when I do dd($three_months) nothing shows up. I only get
Collection {#320 ▼
#items: []
}
Order matters when using SQL's BETWEEN. Your $from value is greater than your $to value. So try swapping them around:
$to = Carbon::now('+2:00');
$from = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
Maybe it's because you are not Formatting DateTime
$from = Carbon::now('+2:00')->format('Y-m-d H:i:s');
$to = $from->copy()->subMonth(3)->format('Y-m-d H:i:s');
Try This code.
Edit: You cant Use copy() method on string. so you can do.
$to = Carbon::now('+2:00')->subMonth(3)->format('Y-m-d H:i:s');

how to show unix timestamp in blade view from created_at or updated_at field in database laravel?

I want to get UNIX timestamp or convert created_at or updated_at date to UNIX timestamp format from database fields (created_at and updated_at) in laravel 5.8 , how can i do this?
this is my code in my controller :
public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}
and in view/archives.blade.php :
<?php echo $data;?>
the result is :
{“created_at”:”2019-03-17 19:10:30″}
but i want the result be like this :
{“created_at”:”1552849830″}
how can get this result?
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
foreach ($collection as $k => &$v) {
$collection[$k]->created_at = strtotime($v->created_at);
}
//var_dump($collection);
or
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
array_walk($collection, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
//var_dump($collection);
Or in your case
public function viewArchives()
{
$data = Archive::select('created_at')->get();
foreach ($data as $k => &$v) {
$v->created_at = strtotime($v->created_at);
}
return view('view.archives', compact('data'));
}
or
public function viewArchives()
{
$data = Archive::select('created_at')->get();
array_walk($data, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
return view('view.archives', compact('data'));
}
This is good place to use array_walk() function.
Add strtotime() view/archives.blade.php :
<?php echo strtotime( $data );?>
With an Eloquent Model one can actually define the $casts per column:
class SomeModel extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime'
];
}
If you want epoch timestamps instead, just remove this cast (which is likely present).
When the timestamp isn't from any Eloquent Model, one still can render it with Blade:
#php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
#endphp
Or the other way around:
#php
echo strtotime( $isodate );
#endphp

Get datetime difference with doctrine

Hi I'm trying to give amount of days and get records between that day and now.
$now = new \DateTime();
$days = 14;
$to = $now->sub(new \DateInterval('P'.$days.'D'));
$qb = $this->createQueryBuilder('c')
$qb->andWhere('c.createdDate BETWEEN :from AND :to')
->setParameter('from', $now)
->setParameter('to', $to);
$qb->getQuery()->getResult();
in my db created_date column and have a record which contain 2018-12-12. But unfortunately query returns no value :(. It would be great help if someone can solve. And I'm using sub to get minus date.
Valid query is:
$from = new \DateTime('-14 days');
$to = (new \DateTime())->setTime(23, 59, 59);
$qb = $this->createQueryBuilder('c')
$qb->andWhere('c.createdDate BETWEEN :from AND :to')
->setParameter('from', $from)
->setParameter('to', $to);
$result = $qb->getQuery()->getResult();
The reason it didn't work for you, is because the \DateTime is a mutable type. By changing a copy, you also changed the previous date object:
$from = new \DateTime();
// below you mutate the $from object, then return its instance
$to = $from->sub(new \DateInterval('P10D'));
// effect is both $from and $to reference the same object in memory
var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');
Will result in:
bool(true)
2018-12-07
2018-12-07
You mapped the property createdDate as datetime in Doctrine. Personally I always use the datetime_immutable type. Instead of DateTime I get to work with DateTimeImmutable, which, compared to DateTime is immutable by design so I don't have to worry about any references:
$from = new \DateTimeImmutable();
$to = $from->sub(new \DateInterval('P10D'));
var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');
Results in:
bool(false)
2018-12-17
2018-12-07

Resources