Laravel - group data by created_at field and apply pagination - php

I need to get previous 10 days activity of a user. In my case i am just getting 10 activity records instead of previous 10 days activity.
*My Code:
$activity = $this->where('user_id', '=', $userId)->paginate(10);
$activities = collect($activity->items())->groupBy(function($item) {
return \Carbon\Carbon::parse($item->created_at)->format('d-M-Y');
});
$activity->setCollection($activities);
dd($activity->toArray());
Output:

You are using paginate which restricts the number of results fetched from the DB. If you want to get previous 10 days activity of a user then you can write your query as:
$activity = $this->where('user_id', '=', $userId)
->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))
->get();

Related

How to use the Larave DB Facade to get the first record with a date close to a particular date

I am trying to get the first transaction that was recorded close to a particular date using the Laravel 8 DB Facade.
I have tried to use it in the following manner
$lastest_transaction = DB::table($targetTable)
->where('date', '<=', date('F'))
->where('id', '=', $client->id)
->where('branch', '=', session('branch'))
->get();
but it's not giving me the correct transaction.
In order to get the record closest to the date, you can sort by the date in descending order, which would make the first record the "largest" date that's less than or equal to what you are searching for:
$lastest_transaction = DB::table($targetTable)
->where('date', '<=', date('F'))
->where('id', '=', $client->id)
->where('branch', '=', session('branch'))
->orderBy('date', 'DESC') // Order by the date in descending order
->first(); // Get the first record

Counting Existing ID's in a different table - laravel

I have two items in a table called products with id's 1 and 2. There is a table called invite which has foreign key product_id for products.
In my controller below, i am trying to count the number of product id's that is existing in the invite table.
eg
Product invite
id name id token product_id user_id
1 cal 1 ..d 1 2
2 del 2 dd.. 2 2
3 mac 3 ..gh4 2 2
As above, id's 1 and 2 exist in the invite table. meaning the total count is 2 (although product id 2 appears twice.
When i run my code below, i get a count of 1 instead of 2. What could i be missing out, please?
NB: in this case, i am user just one user
Controller
public function dashboard()
{
$products = Products::orderBy('created_at', 'desc')
->where('user_id', Auth::user()->id)->get();
$get_products_id = [];
foreach($products as $product){
$get_products_id[] = $product->id;
}
$implode_data = implode(',',$get_products_id);
$count_existing_products =
Invite::where('product_id',$implode_data)
->where('user_id', Auth::user()- >id)->get()->count();
return view('dashboard', compact('count_existing_products'));
}
View
<h1>{{count_existing_products}}}</h1>
For WHERE IN clause laravel uses special whereIn() method where you pass array, not string. So, your query becomes:
Invite::whereIn('product_id', $get_products_id)
->where('user_id', Auth::user()->id)
->distinct() // added `distinct` call to get distinct values
->get()
->count();
If distinct does not work, try to groupBy:
Invite::whereIn('product_id', $get_products_id)
->where('user_id', Auth::user()->id)
->groupBy('product_id')
->get()
->count();
There is no need to use implode. you can use whereIn instead of where.
Invite::whereIn('product_id',$get_products_id)
->where('user_id', Auth::user()- >id)->get()->count();

Count the users created within last week in Laravel

How to use carbon and count the users created in the last 7 days. On blade, I have a table that shows the total of users created per day that has this syntax (example is for today)
$getusertoday = MemberProfile::where('encoded_by', '=', $profile->name)
->whereDate('created_at', '=', $today )->count();
But in the last column, which is the Weekly Total, I must total everything.
$getusertoday = MemberProfile::where('encoded_by', '=', $profile->name)
->whereDate('created_at', '>=', date('Y-m-d H:i:s',strtotime('-7 days')) )->count();

Laravel multiple counts with condition

I'm tring to retrieve the totals of items from a table but can't get my head around it.
What I'm trying to achieve is this:
I have a table 'users' with the following columns:
Admin - yes/no
Moderator - yes/no
I am trying to retrieve the total of the items in the table but also the total of items in the table with admin = 'yes' OR moderator = 'yes'. The reason for this is to display the totals in one table.
Below is my sample code:
$date = new DateTime('tomorrow -360 month');
$usersPerDay = User::select(array(
DB::raw('DATE(`created_at`) as `date`'),
DB::raw('COUNT(*) as `count`'),
this is where I have the problem - Is it possible to do something like
this
DB::raw('COUNT(*) as "type" WHERE admin= "yes" OR moderator= "yes"')
))
->where('created_at', '>', $date)
->groupBy('date')
->orderBy('date', 'DESC')->get();

Laravel get rows with specific day and month

I have the following query in laravel:
$eventos = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
->where('tbl_users.birth_date', '>=', date("m-d")) //my error
->where('tbl_events.year', '>=', date("Y"))
->get();
I have a users table (tbl_users), with the date of the birthdays of each user. And an events table (tbl_events), which records the anniversary of each user. Thus creating a table that will get the next birthdays.
My birth_date is type "yyyy-mm-dd". The table events is the year. I want to get the next event on the current day and year.
ie I think the anniversary date must be greater than the current month and day, and the event with the top year to the current year
Format the birth_date to mm-dd first before comparing it to date('m-d'), like so:
$eventos = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
->whereRaw("DATE_FORMAT( tbl_users.birth_date, '%m-%d') >= ?", array(date('m-d')))
->where('tbl_events.year', '>=', date("Y"))
->get();
Update
If your tbl_events doesn't have a full date attribute, you could do this in 2 queries:
First, get the remaining events of this year:
$events_this_year = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
->whereRaw("DATE_FORMAT( tbl_users.birth_date, '%m-%d') >= ?", array(date('m-d')))
->where('tbl_events.year', '=', date("Y")) // Get remaining events this year
->get();
Second, get the events for next years:
$events_following_year = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
->where('tbl_events.year', '>', date("Y")) // Get events for upcoming years
->get();
Then merge them
$eventos = $events_this_year->merge($events_following_year);

Categories