Intval function in Laravel eloquent query - php

I am doing filter script. User write age_to and I get users with maximum age. The problem is that my in my users table is only full date of birth. How can I get all data? I think intval function is good but I do not know how to use it in mysql query.
$user = User::with('user_x')->whereHas('user_x', function($query) use ($request) {
$birth_date = Carbon::now()->subYears($request->age_to)->toDateString();
return $query->where('date_of_birth', '<=', $birth_date);
})->get();

Intval probably won't do what you want, but Carbon may. Since you're going for age, then use Carbon's date setters:
$birth_date = Carbon::now()->subYears($request->age_from)->toDateString(); // Sets the birth date to today's date minus the requested years
Then you can use it in your query:
$user = User::with('user_x')->whereHas('user_x', function($query) use ($birth_date) {
return $query->where('date_of_birth', '<=',$birth_date);
})->get();

Related

How to get less than data of selected month of year in laravel?

i have a table where all data of students. i need only less than month data of selected month of year. i have date column data like these.
registrationdate
2022-01-31
2021-12-01
2022-07-01
2021-11-12
2021-10-10
2022-01-07
2020-08-26
if I select month 12 and year 2021 I need only previous data of December 2021
$month=12 and $year =2021
$selectedmonthMalestudents = \DB::table('students')
->whereRaw('extract(month from registrationdate) = ?','<' [$month])
->whereRaw('extract(year from registrationdate) = ?', [$year])
->count();
Please Help me How to do these...
All you need to call the whereMonth and whereYear method of eloquent. I have doubts whether that can work with DB::table but you can use the model anyway.
$selectedmonthMalestudents = \DB::table('students')
->whereMonth('salary_date', $month)
->whereYear('salary_date', $year)
->count();
personal suggestions:- always use model instead of DB::table();
First of all you should never use a Raw SQL statement in laravel, well except in some scenarios which it is absolutely necessary, because of security issues
so in your controller, you can use Carbon
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->where('registrationdate', '<', $date)->get();
return response()->json([compact('result'), 200]);
}
or use Laravel's Eloquent ORM Map collection method like
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->filter(function($std, $key) {
$created_at = Carbon::now($std['registration_date']);
if($create_at->isBefore($date)) {
return true;
}
})->get();
return response()->json([compact('result'), 200]);
}

eloquent filter query by date in controller

Hi I have this eloquent function in my controller to return rows to my view , I want to limit to filter by today's date
here is my function:
$rows = \App\Models\WeightsJournalView::where(function($query) use($request){
$query->orwhere('id','like',$request['search'])
->orwhere('currentAvgWeightMale','like',$request['search'])
->orwhere('currentAvgWeightFemale','like',$request['search'])
->orwhere('pastAvgWeightMale','like',$request['search'])
->orwhere('pastAvgWeightFemale','like',$request['search'])
->orwhere('batch_name','like',$request['search'])
->orwhere('barn_name','like',$request['search'])
->orwhere('farm_name','like',$request['search'])
->orwhere('created_at','like',date('Y-m-d'));
})->orderBy($request['sort'],$request['order'])
->skip($request['offset'])
->take($request['limit'])
->get();```
you can use:
orWhereBetween('created_at',[Carbon::now()->startOfDay(),\Carbon::now()->endOfDay()])
\Carbon::now()->startOfDay() will give you the very beginning of today
\Carbon::now()->endOfDay() will give you the very ending of the day
or you can use:
orWhereDate('created_at',Carbon::now()->toDateString())
orWhereDate will take the only date part of dateTime column, and it value will be compared to date string of now.
That should do it if I understood your problem correctly
$rows = \App\Models\WeightsJournalView::whereDate('created_at', '=' , date('Y-m-d'))
->andWhere(function ($query) {
$query->where('id','like',$request['search'])
->orWhere('currentAvgWeightMale','like',$request['search'])
->orWhere('currentAvgWeightFemale','like',$request['search'])
->orWhere('pastAvgWeightMale','like',$request['search'])
->orWhere('pastAvgWeightFemale','like',$request['search'])
->orWhere('batch_name','like',$request['search'])
->orWhere('barn_name','like',$request['search'])
->orWhere('farm_name','like',$request['search'])
->orWhere('created_at','like',date('Y-m-d'));
})->orderBy($request['sort'],$request['order'])
->skip($request['offset'])
->take($request['limit'])
->get();```
The first solution worked after I tweaked it like the following thanks Guys :
$rows = \App\Models\WeightsJournalView::whereDate('created_at', '=' , date('Y-m-d'))
->Where(function ($query) use($request){
$query->where('id','like',$request['search'])
->orWhere('currentAvgWeightMale','like',$request['search'])
->orWhere('currentAvgWeightFemale','like',$request['search'])
->orWhere('pastAvgWeightMale','like',$request['search'])
->orWhere('pastAvgWeightFemale','like',$request['search'])
->orWhere('batch_name','like',$request['search'])
->orWhere('barn_name','like',$request['search'])
->orWhere('farm_name','like',$request['search']);
})->orderBy($request['sort'],$request['order'])
->skip($request['offset'])
->take($request['limit'])
->get();

Get user with specific age using date from database and carbon

I am doing requests when I want to get users with specific age. But I do not know how to get users from database. For example if user has 19 yo, I want users from age 12 - I get that user. If he has 20 - not. Can you help me with my code? Because it doesn't work.
Here's my code:
if ($request->has('age_from'))
{
$user = User::with('user_data')->whereHas('user_data', function($query) use ($request) {
$birth_date = Carbon::now()->subYears($request->age_from)->toDateString();
return $query->where('date_of_birth', '>=', $birth_date);
})->get();
}
You shouldn't need to format the Carbon object, Laravel and Carbon work seamlessly in database queries:
$user = User::with('user_data')->whereHas('user_data', function($query) use ($request) {
$query->where('date_of_birth', '>=', Carbon::now()->subYears($request->age_from));
})->get();

Laravel date format in where condition

I have this code
use Carbon;
$now = Carbon::now()->toDateString();
So i get the date without the time
public funtion test($brandid){
$nbofsale=DB::table('st_nsales')
->where('brand_id', $brandid)
->where('eodate', $now)
->get();
return $nbofsale;
}
The eodate field in the select is datetime. I want to put it in this query as date only and not to change the field type in database.
Any ideas?
If eodate is a timestamp, you don't need to convert it to a date string:
$nbofsale = DB::table('st_nsales')
->where('brand_id', $brandid)
->whereDate('eodata', Carbon::today()->toDateString());
->get();
Another way to get record for today:
$nbofsale = DB::table('st_nsales')
->where('brand_id', $brandid)
->where('eodata', '>', Carbon::now()->startOfDay());
->get();

Laravel Eloquent get results grouped by days

I currently have a table of page_views that records one row for each time a visitor accesses a page, recording the user's ip/id and the id of the page itself. I should add that the created_at column is of type: timestamp, so it includes the hours/minutes/seconds. When I try groupBy queries, it does not group same days together because of the seconds difference.
created_at page_id user_id
========== ======= =======
10-11-2013 3 1
10-12 2013 5 5
10-13 2013 5 2
10-13 2013 3 4
... ... ...
I'd like to get results based on views/day, so I can get something like:
date views
==== =====
10-11-2013 15
10-12 2013 45
... ...
I'm thinking I'll need to dig into DB::raw() queries to achieve this, but any insight would help greatly, thanks
Edit: Added clarification of created_at format.
I believe I have found a solution to this, the key is the DATE() function in mysql, which converts a DateTime into just Date:
DB::table('page_views')
->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
However, this is not really an Laravel Eloquent solution, since this is a raw query.The following is what I came up with in Eloquent-ish syntax. The first where clause uses carbon dates to compare.
$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
->groupBy('date')
->orderBy('date', 'DESC')
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "views"')
));
You can use Carbon (integrated in Laravel)
// Carbon
use Carbon\Carbon;
$visitorTraffic = PageView::select('id', 'title', 'created_at')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y'); // grouping by years
//return Carbon::parse($date->created_at)->format('m'); // grouping by months
});
Here is how I do it. A short example, but made my query much more manageable
$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
->groupBy(DB::raw('Date(created_at)'))
->orderBy('created_at', 'DESC')->get();
Like most database problems, they should be solved by using the database.
Storing the data you want to group by and using indexes you can achieve an efficient and clear method to solve this problem.
Create the migration
$table->tinyInteger('activity_year')->unsigned()->index();
$table->smallInteger('activity_day_of_year')->unsigned()->index();
Update the Model
<?php
namespace App\Models;
use DB;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class PageView extends Model
{
public function scopePerDay($query){
$query->groupBy('activity_year');
$query->groupBy('activity_day_of_year');
return $query;
}
public function setUpdatedAt($value)
{
$date = Carbon::now();
$this->activity_year = (int)$date->format('y');
$this->activity_day_of_year = $date->dayOfYear;
return parent::setUpdatedAt($value);
}
Usage
$viewsPerDay = PageView::perDay()->get();
You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:
Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
->groupBy('date')
->get();
I had same problem, I'm currently using Laravel 5.3.
I use DATE_FORMAT()
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
Hopefully this will help you.
PageView::select('id','title', DB::raw('DATE(created_at) as date'))
->get()
->groupBy('date');
To group data according to DATE instead of DATETIME, you can use CAST function.
$visitorTraffic = PageView::select('id', 'title', 'created_at')
->get()
->groupBy(DB::raw('CAST(created_at AS DATE)'));
Warning: untested code.
$dailyData = DB::table('page_views')
->select('created_at', DB::raw('count(*) as views'))
->groupBy('created_at')
->get();
I know this is an OLD Question and there are multiple answers. How ever according to the docs and my experience on laravel below is the good "Eloquent way" of handling things
In your model, add a mutator/Getter like this
public function getCreatedAtTimeAttribute()
{
return $this->created_at->toDateString();
}
Another way is to cast the columns
in your model, populate the $cast array
$casts = [
'created_at' => 'string'
]
The catch here is that you won't be able to use the Carbon on this model again since Eloquent will always cast the column into string
Hope it helps :)
Using Laravel 4.2 without Carbon
Here's how I grab the recent ten days and count each row with same day created_at timestamp.
$q = Spins::orderBy('created_at', 'desc')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->take(10)
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "views"')
));
foreach ($q as $day) {
echo $day->date. " Views: " . $day->views.'<br>';
}
Hope this helps
You could also solve this problem in following way:
$totalView = View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
->groupBy(DB::raw('Date(read_at)'))
->orderBy(DB::raw('Date(read_at)'))
->get();
this way work properly and I used it in many projects!
for example I get data of views the last 30 days:
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
If you want to get the number of views based on different IPs, you can use the DISTINCT like below :
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
->groupBy('date')
->get();
You can easily customize it by manipulating the columns name
you can use the following code to group them by the date, since you have to parse both in the selection query and in the groupBy method:
$counts = DB::table('page_views')->select(DB::raw('DATE(created_at) as created_at'), DB::raw('COUNT(*) as views'))->
groupBy(DB::raw('DATE(created_at)'))->
get();
in mysql you can add MONTH keyword having the timestamp as a parameter
in laravel you can do it like this
Payement::groupBy(DB::raw('MONTH(created_at)'))->get();
I built a laravel package for making statistics : https://github.com/Ifnot/statistics
It is based on eloquent, carbon and indicators so it is really easy to use. It may be usefull for extracting date grouped indicators.
$statistics = Statistics::of(MyModel::query());
$statistics->date('validated_at');
$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())
$statistics->indicator('total', function($row) {
return $row->counter;
});
$data = $statistics->make();
echo $data['2016-01-01']->total;
```
Get pages views (or whatever), group my year-month-day and count for each date:
PageView::get()
->groupBy(fn($pv) => $pv->created_at->format('Y-m-d'))
->map(fn($date) => count($date));

Categories