Laravel get most out of the database - php

I'm having a tracker in Laravel 4 and I was wondering, how can I get the 'most' from my table.
So want I want is to have the day that had the most visitors.
My table structure looks like this:
So, my controller looks like this:
public function index()
{
$begin = date('Y-m-01');
$end = date('Y-m-t');
$visits = Tracker::selectRaw('date, count(ip)')->groupBy('date')->whereRaw("date between '$begin' and '$end'")->get();
//get total visits per month
$get_visits = Visitor::whereRaw("date between '$begin' and '$end'")->count();
// get average visits
// transform dates to DateTime objects (we need the number of days between $begin and $end)
$begin = new \DateTime($begin);
$end = new \DateTime('now');
$diff = $end->diff($begin); // creates a DateInterval object
$days = (int)$diff->format('%a'); // %a --> days
$average_visits = $get_visits / $days;
return View::make('admin.home.index')->with('stats', $visits)
->with('get_visits', $get_visits)
->with('average_visits', $average_visits);
}
What I want as an output:
We had the most visitors on 18/06/2015 (542 visitors)
For example.
Thanks!

You can SELECT the date ORDER BY the amount of visitors DESCENDING and LIMIT by 1. This is basic mysql. How to use this in laravel, is in the documentation.
Order by desc:
->orderBy('visits', 'desc')
Limit:
->take(1)
My example query is based on a system that has a column which counts the visits(which your structure doesn't have). So let me help you with your structure.
You want to have it by date so you basically GROUP BY date:
->groupBy('date')
From this query you want to have the amount of rows that belong to that date. So you use COUNT:
->count()
This is all based on that you know stuff about queries. This is all according to the query builder.

Related

How to compare created_at timestamp with Carbon date In laravel?

I have orders table , I want to get orders that have been created at this month only (delivery process happens at the same day).
I want to compare between the carbon date which refers to this current month with the created_at field of type timestamps for orders.
This is my attempt:
$month = Carbon::today();
$currentMont = $month->month;
$thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
dd($thisMonthOrders);
The output that it gives me is an empty array.
You'll need to use the MONTH function in MySQL, along with a whereRaw:
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereRaw('MONTH(created_at) = ?',[$currentMont])
->get();
However, you'll have issues when you have multiple years, unless you also add in a YEAR check. You might have better luck with whereBetween instead.
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereBetween('created_at',[$start, $end])
->get();

Difference between two dates in MySQL and display in php

I have 2 dates a Checkin Date and Check out Date on a booking system. i want to find out the amount of days from checkin to checkout. I can run a Select query in mysql and get my results. But i am trying to work out ho to do it easy in php.
I do not know how to display the query results in each row of the bookings
My sql query:
SELECT timestampdiff(DAY, bookeddate, bookeddateout) AS days
FROM users
this works fine and creates temp column called days.
I am newish to this and i am not sure what to do. sorry guys. Al i want is to display the days a person is staying in a column on the users table.
Yo can use this function i write call as dataDiff($firstDay,$lastDay)
function dataDiff($date1, $date2) {
$dateDiff = 0;
$nextday = $date1;
while($nextday <= $date2) {
$nextday = date("Y-m-d", strtotime("+1 day", strtotime($nextday)));
$dateDiff++;
}
return $dateDiff;
}

how to filter results inside where clause in laravel?

I am new to laravel, I am building a small application which alerts when event date is a week away from current date. Here is my controller code
public function index()
{
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::
where('domain_ex_date','>',date('Y-m-d'))
->get();
}
The domain_ex_date is in the format (YYYY-mm-dd) stored with the help of Carbon. The line where('domain_ex_date','>',date('Y-m-d')) gets me whole record when the domain_ex_date is away from the current date. i.e 2017-06-12 > 2016-09-15 gets the whole record. Here what i want to do is , i want to filter and get the only records which is only a week away from the current date. How do i do this ? i have tried like subweek() and subdays() but nothing helped.
I should get the record only when it satisfies this condition domain_ex_date - current date = 7
You can use strtotime():
domain_details:: where('domain_ex_date','<',date('Y-m-d',strtotime("+7 days")))
-> where('domain_ex_date','>',date('Y-m-d'))
->get();
Use Carbon!
Carbon is a build in date-extension ... Try it! :)
$week = Carbon::now()->addWeek();
$now = Carbon::now();
domain_details::where("domain_ex_date","<" $week)
->where("domain_ex_date", ">" $now)
->get()
Or you could also use the addDays($days) method!
$week = Carbon::now()->addDays(7);
I used carbon and this is what worked well for me
$week = Carbon::now()->subWeek();
$now = Carbon::now();
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::where("domain_ex_date",">", $week)
->where("domain_ex_date", "<" ,$now)
->get();

Repeat insert query with a different date given by a frequency

I'm building a system where an user can register activities. However the activities registered can repeat over the course of the year.
In order to prevent having the need that the user has to fill in the form to create an activity multiple times for each different date, I had the idea to add a textbox and a dropdown to the form to allow the user to fill in a frequency. The user can fill in a number in the textbox (for example "2") and select a value from the dropdown (for example "week"). So from that selection the activity has to be added to the database for the next 2 weeks on the same day.
However I have no idea how to let PHP adjust the date and add exactly 7 days to the selected date and repeat the same insert query with the new date, for every week/month/year selected from the given frequency.
EDIT 1:
I've tried this so far:
while ($i> 0)
{
$query2 = $this->db->connection->prepare("INSERT INTO activity(Act_Startdate) values (?)");
$query2->bind_param("s", $Startdate);
$query2->execute();
$Dates = date('d-m-Y', strtotime($Startdate . '+ 1 days'));
$Startdate = date('d-m-Y', strtotime($Dates));
$i--;
}
The first date insertion works, but the second one results 0000-00-00.
Read more about :
Date Time in PHP.
Date Interval in PHP
$numberPostedByUser = $_POST['your_input_name_in_form'];
$currentDate = new \DateTime(); // Getting current date
$iterator = 1;
while ($iterator <= $numberPostedByUser) {
$currentDate->add(new \DateInterval('P1D')); // Adding interval of one day in current date
$startDate = $currentDate->format('Y-m-d H:i:s'); // converting that day in convenient format we required
$query2 = $this->db->connection->prepare("INSERT INTO activity(Act_Startdate) values (?)");
$query2->bind_param("s", $startDate);
$query2->execute();
$iterator++; // increasing iterator for next loop
}
Hope may this code will help you.

MySQL Query with Idiorm and Date Issue

I want to use a chart on some of my data and generate the values based on selected dates (with a date picker). I've stolen most of the stuff on the web and might have only a simple questions.
Here is the Idiorm query:
if (isset($_GET['start']) AND isset($_GET['end'])) {
$start = $_GET['start'];
$end = $_GET['end'];
$data = array();
// Select the results with Idiorm
$results = ORM::for_table('tbl_data')
->where_gte('date', $start)
->where_lte('date', $end)
->order_by_desc('date')
->find_array();
// Build a new array with the data
foreach ($results as $key => $value) {
$data[$key]['label'] = $value['date'];
$data[$key]['value'] = $value['rev'];
}
echo json_encode($data);
}
The $start and $end are from my datepicker and in yyyy-mm-dd format. The only thing I don't know how to do is how to change the ->where_gte statement. As you can see it's querying the db for the field date. In my db I have three fields, year, month and day.
Is there a way to combing the three fields year, month and day into one expression i.e. maybe ->where_gte('year'&'month'&'day', $start)???
I tried searching and searching but maybe have the wrong keywords or to less knowledge.
Thanks in advance for any help!
Since you have three fields in the DB, you need three where_gte clauses:
...
->where_gte('year', substr($start, 0, 4) // or most suitable date_format
->where_gte('month', substr($start, 5, 2) // or most suitable date_format
...
Hope it helps.
You can manage date format using MySql DATE_FORMAT() Function. E. G.:
// Select the results with Idiorm
$results = ORM::for_table('tbl_data')
->where_gte('date', "DATE_FORMAT($start, '%Y-%m-%d')")
->where_lte('date', "DATE_FORMAT($end, '%Y-%m-%d')")
->order_by_desc('date')
->find_array();

Categories