How to query created_at field in Laravel - laravel

When trying to find all records where the created_at time is larger than a certain value, it does not seem to work.
For example I have tried this:
return Foo::where('created_at', '>', '1457408361')->get();
But it keeps returning all the records!

Use the whereDate() query method:
$date = Carbon::yesterday(); // Create date however you want
Foo::whereDate('created_at', '>', $date);
If you do these types of queries a lot, I’d consider wrapping it into a query scope:
use DateTimeInterface;
class Foo extends Model
{
public function scopeCreatedAfter(DateTimeInterface $date)
{
return $query->whereDate('created_at', '>', $date);
}
}
Usage:
Foo::createdAfter($date)->get();

You can always use Carbon to convert the UNIX timestamp:
Foo::where('created_at', '>=', Carbon::createFromTimestamp(1457408361))->get();
So you can convert your integer to Carbon instance and compare it as above.
You can read about Carbon here: http://carbon.nesbot.com/docs/

Related

Laravel Carbon class timestamp

In my laravel project I didn't migrate the table with timestamp(created_at). I used to get the time with a date column.
I need to filter the data from that table so that I used Laravel Carbon class.
This is my function for filter the data
public function getWeeklyData()
{
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
return view('admin.pages.tables.weeklydata',['weeklydata' => $weeklydata]);
}
But there is no output.
Some times my date format is different from Carbon class date format.
If any solution for this?
When you use Carbon it will carbon object return. so try below
$data = \Carbon\Carbon::today()->subDays(7)->format('Y-m-h');
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
and you can use whereDate also
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->whereDate('date','>=',$data)
->get();

Laravel query where date more recent than current time

I am using a Laravel eloquent model.
I want to add a query condition where start_time later than now.
For example:
Model::whereAfterNow('start_time')->all()
Can you help me??
it looks like you need a query scope (https://laravel.com/docs/5.6/eloquent#local-scopes).
assuming 'start_time' is a model property (database field) containing a some representation of time, and you want a scope that returns all models where 'start_time' later than now...
How you structure your code depends on what format your dates are stored in your database.
For example, if you are using epoch timestamps, then in your Model.php:
public function scopewhereAfterNow($query)
{
return $query->where('start_time', '>', \Carbon\Carbon::now()->timestamp);
}
or you could use the DB facade:
public function scopewhereAfterNow($query)
{
return $query->where('start_time', '>', DB::raw('unix_timestamp(NOW())'));
}
which you might call like:
$results = Model::whereAfterNow()->get();
If 'start_time' returns a DateTime string you can try:
Model::where('start_time', '>', \Carbon\Carbon::now()->toDateTimeString())->get();
If 'start_time' only returns time then you can try:
Model::where('start_time', '>', \Carbon\Carbon::now()->toTimeString())->get();

Add date on Laravel

When i am using this code it shows an error "Call to a member function addDays() on string"
public function showJobCategoryContent($id)
{
$jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
$jobsInfoById = $jobsInfoById->map(function ($job) {
return $job->created_at->addDays(30);
});
return $jobsInfoById->pluck('created_at');
}
Because you're using DB instead of Jobs, you are getting back raw database data instead of a carbon instance. If you did the same thing with Jobs, you'd get models and the dates would be Carbon:
$jobsInfoById = Jobs::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
To fix it without using Eloquent, do:
use Carbon\Carbon; //including Carbon already
$jobsInfoById = $jobsInfoById->map(function ($job) {
return ['created_at' => Carbon::parse($job->created_at)->addDays(30)];
});
Carbon instance is created when you are doing the map on the result.

Laravel whereDate() not working

I have used below query to get result with some codition in my controller
$events = Event::whereHas('topic', function ($q) {
$q->where('delete_status', 0);
})
->where('status', 1)
->where('delete_status', 0);
And in my view file i have used this variable thrice to check with Date like below
$events->where('type', '!=', 2)->whereDate('start_date', '>=', \Carbon\Carbon::now())->get()
And
$events->where('type', 2)->whereDate('start_date', '>=', \Carbon\Carbon::now())->get()
And
$events->whereDate('start_date', '<', \Carbon\Carbon::now())->get()
Because i want to get the result based on past date or present date. If i use get in controller query i got error of whereDate() does not exists
So i have used get() method in view file.
I cannot get record from second and third query but I can only get record from 1st query in view file.
Any solution?
$events is an collection which doesn't have whereDate method, what you might be looking for is the filter() to filter your collection in your views. Hence you could do so
$filtered_events =
$events->where('type', 2)
->filter(function ($item) {
return Carbon::parse($item->start_date)->gte(Carbon::today());
});
Reference

How to get items from collection by created_at date with using only Y-m-d part?

I have a collection with records that include the created_at row. Now i want to get specific rows by date without time. I mean :
$users->whereLoose('created_at', '2016-11-23')
of course this returns empty but the format I need to use is "Y-m-d" without the "H:i:s" part. How can use this format to get records from the collection?
You could also use the filter method and the isSameDay() method.
$date = \Carbon\Carbon::parse('2016-11-23');
$usersForDate = $users->filter(function ($user) use ($date) {
return $user->created_at->isSameDay($date);
});
Hope this helps!
You can do this:
$date = Carbon::parse('2016-11-23');
$users->where('created_at', '>', $date->startOdDay())
->where('created_at', '<', $date->endOfDay());
Or you could try this:
$users->whereDate('created_at', '=', '2016-11-23');
You can try using the map() function on the collection per the docs https://laravel.com/docs/5.2/collections:
https://laravel.com/docs/5.2/collections#method-map
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});

Resources