curdate() query not working in laravel 5.2 - php

I have one problem in my query is CURDATE() not working in my laravel 5.2
AbsenController#index
$now = time();
$absen = Absen::with('siswa')->where('level', '=', 'Siswa', 'AND',
'created_at', '<=', 'CURDATE()')->get();
return view('absen.index')->with('data', $absen);
and this is record in my Absen Table

I am not familiar with your where sytnax. Try including separate terms for each of the two conditions in your WHERE clause:
$absen = Absen::with('siswa')
->where('level', '=', 'Siswa')
->where('created_at', '<=', DB::raw('curdate()'))
->get();
As a variant, you could also use whereRaw() to handle the condition involving CURDATE():
$absen = Absen::with('siswa')
->where('level', '=', 'Siswa')
->whereRaw('created_at <= curdate()')
->get();
Conditions are ANDed together by default, which is the relationship you have between your two conditions. Look into orWhere() if you want to OR together conditions in the WHERE clause.

$now = time();
$absen = Absen::with('siswa')->where('level', 'Siswa')->where('created_at','<=',\Carbon\Carbon::now())->get();
return view('absen.index')->with('data', $absen);

Related

Subquery of two related tables in laravel

I want to write the following query in Laravel 5.
SELECT *
FROM loans
WHERE loanAmount > (SELECT IFNULL(SUM(paidLoanAmount), 0)
FROM paid_loans WHERE loanId = loans.id);
I have tried the following, but subquery of PaidLoan seems not work due to loans.id or something else I don't notice.
Loan::where(
'loanAmount',
'<=',
PaidLoan::where('paid_loans.loanId', 'loans.id')
->get()
->sum('paidLoanAmount')
)->get();
You can use a leftJoin on the loan and just add a normal condition.
$payedLoans = Loan::leftJoin('paid_loans', 'paid_loans.loanId', '=', 'loans.id')
->where('loanAmount', '<=', \DB::raw("IFNULL(sum('paid_loans.paidLoanAmount'), 0)"))
->groupBy('loans.id')
->get();

Laravel datetime created_at

I have a question. If created_at in my database is datetime and I want to make a query like this
whereDate('created_at', '=', date('Y-m-d'))
I get nothing as a result. How can i handle this situation ?
Another case: I want
whereDate('created_at', '=', date('M'))
You can use other helper functions maybe:
$query->whereYear('created_at', '=', date('Y'))
->whereMonth('created_at', '=', date('m'))
->whereDay('created_at', '=', date('d'));
Assuming you are using MySQL, you could use whereRaw:
whereRaw('created_at = CURDATE()')
For your second case:
whereRaw("month_name = DATE_FORMAT(CURDATE(), '%b')")
First Query: You can use Carbon specifying date format (date without time toDateString() / date with time toDateTimeString() ).
$query->whereDate('created_at', '=', Carbon::today()->toDateTimeString());
Second Query: Just query on whereMonth
$query->whereMonth('created_at', '=', date('m'));

(laravel) Two ORDER BY clauses and a LIMIT

This is some sorting:
I want to list 20 best posts based on "views".
then, sort it based on "created_at".
How to do it?
Heres my current code (which work, but doesnt sort by "created_at"):
$this->data['today_post'] =
Posts::orderBy('views', 'desc')
->orderBy('created_at', 'desc')
->whereRaw('created_at >= NOW() - INTERVAL 1 DAY')
->limit(20)->get();
You can write this. Hopefully this will solve your problem
$this->data['today_post'] =
Posts::orderBy('views', 'desc')
->orderBy('created_at', 'desc')
->whereDate('created_at', Carbon::today()->toDateString())
->limit(20)
->get();
Also add use Carbon\Carbon; at the beginning of your controller.
Get a collection from database first
$x = Posts::whereRaw('created_at >= NOW() - INTERVAL 1 DAY')->orderBy('views', 'desc')->limit(20)->get();
Then sort the collection
Descending:
$this->data['today_post'] = $x->sortByDesc('created_at');
Ascending:
$this->data['today_post'] = $x->sortBy('created_at');
You can simply sort the result collection. Keeping your code, add the following:
$this->data['today_post'] = $this->data['today_post']->sortBy('created_at');

Find By Date Laravel 5.2

I have some problem with searching by existing date.
In Model:
$date = '2016-01-14';
public static function getByDate($date)
{
$query = self::select('date', DB::raw('SUM(test_count) as test'))
->whereDate('date', '=', $date)
->groupBy('date')
->orderBy('date', 'ASC')
->get();
}
But I didn't get a result, because this code creates SQL:
select `date`, SUM(test_count) as test from `test_table` where date(`date`) = 2016-01-14 group by `date` order by `date` asc limit 1
Not quoted around of date => 2016-01-14
How to fix it?
I try to use whereRaw with params, for example:
return $query->whereRaw("date= ?",[$date]);
but it did not help...
You need to change the ->whereDate('date', '=', $date) to this:
->where('date', '=', $date)
Or you can use this:
->whereDate($date)
So, it's obvious that, you can use either ->whereDate($date) or ->where('date', '=', $date) because whereDate is a dynamic method and in this case, it'll become: where('date', '=', $date).

Laravel Query Builder - Ordering on a Custom Column

I want to sort my Laravel query builder results on a custom column (concat of first_name and last_name).
What I have done is-
$summary = DB::table('service_rating')
->join('partners', 'partners.id', '=', 'service_rating.partner_id')
->join('users', 'users.id', '=', 'partners.user_id')
->select(
DB::raw("CONCAT( users.first_name,' ', users.last_name) as lawn_pro"),
DB::raw ('AVG(service_rating.rating) as rating'),
DB::raw ('COUNT(service_rating.rating) as jobs'),
DB::raw ('SUM(service_rating.rating) as payout')
)
->where('customer_id', '=', Auth::user()->id)
->whereRaw('service_rating.created_at >= DATE(NOW()) - INTERVAL '.$no_of_day_to_show.' DAY')
->groupBy('service_rating.partner_id')
->orderBy('lawn_pro', 'asc');
So, I am getting error for this line -
->orderBy('lawn_pro', 'asc');
And error is like this-
Can anyone please help ?
Apparently you are using the count() function on your query, this ignores the select attributes because we only want to know the count of the rows. Because of this, lawn_pro is not available in the query.
I would suggest to execute the query and then count the available rows.
$rows = $summary->get();
$count = count($rows);

Categories