Laravel query Builder with DATE mysql function - mysql

Hi I have a query in my laravel project which should retrieve dates between ranges. My query is:
$dateFrom = date("Y-m-d", strtotime($request->dateFrom));
$dateTo = date("Y-m-d", strtotime($request->dateTo));
$posts = DB::table('posts')->join('categories','posts.category_id','=','categories.id')->
join('users','posts.user_id','=','users.id')
->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
->whereBetween('posts.created_at',[$dateFrom,$dateTo])
->get();
I'd like to use DATE mysql_function on column posts.created_at but I don't know how could I do it. Below query dosen't work:
$dateFrom = date("Y-m-d", strtotime($request->dateFrom));
$dateTo = date("Y-m-d", strtotime($request->dateTo));
$posts = DB::table('posts')->join('categories','posts.category_id','=','categories.id')->
join('users','posts.user_id','=','users.id')
->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
->whereBetween('DATE(posts.created_at)',[$dateFrom,$dateTo])
->get();
I would be greatful for help. Best regards ;)

change ->whereBetween('DATE(posts.created_at)'
to ->whereBetween(DB::raw('DATE(posts.created_at)'))
if you want to add some raw expression in a query you can use DB::row method as mentioned in laravel documentation

Try using Carbon like this:
use Carbon\Carbon;
...
$dateFrom = Carbon::parse($request->dateFrom);
$dateTo = Carbon::parse($request->dateTo);
$posts = DB::table('posts')
->join('categories','posts.category_id','=','categories.id')
->join('users','posts.user_id','=','users.id')
->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
->whereBetween('posts.created_at',[$dateFrom,$dateTo])
->get();

Related

how to make query in laravel 7

i have query in my sql like this
SELECT villages.id FROM gocement.villages LEFT JOIN gocement.districts ON villages.district_id = districts.id Where villages.name = 'kebonagung' && districts.name ='sukodono';
from mysql i got the data village.id = 81
'kebonagung' it is can change using row['kelurahan'] from my code here
$village_name = $row['kelurahan'];
$district_name = $row['kecamatan'];
$query = Village::select('villages.*');
$query->leftJoin('districts', 'villages.district_id', '=', 'districts.id');
$query->where('villages.name', '=', $village_name);
$query->where('districts.name', '=', $district_name);
$hasil = $query->get('villages.id');
dd($hasil);
here what i have try using laravel code.
but when i run my laravel i got like this :
my question is how to fix my queries in my laravel code to get 81
Change it to
$query = Village::select('villages.id');
also change
$hasil = $query->get();
see this
$query = Village::select('villages.id');
$query->leftJoin('districts', 'villages.district_id', '=', 'districts.id');
$query->where('villages.name', '=', $village_name);
$query->where('districts.name', '=', $district_name);
$hasil = $query->pluck('id');
dd($hasil->all()[0]);
it will return exactly 81

how to run mysql query in Laravel

I want to transform my MySql query into a Query in Laravel but I really don't know how to do this. I don't know how to rename in FROM like in SQL
My query is the following one :
SELECT f2.* FROM formation f2 WHERE f2.theme_id IN
(SELECT f.theme_id FROM user_formation uf JOIN formation f ON uf.formation_id = f.id WHERE uf.user_id = 2)
AND f2.id NOT IN
(SELECT formation_id FROM user_formation WHERE user_id = 2);
I tried something like this but ...
$q = Formation::query()
->from('formation AS f2')
->whereIn('f2.theme_id', function($r)
{
$r->select('f.theme_id')->from('user_formation AS uf')
->join('formation', function($join)
{
$join->on('uf.formation_id', '=', 'f.id')
->where ('uf.user_id', '=', $id)
});
});
->whereNotIn('f2.id', function($s){
$s->select('formation.id')
->from('user_formation')
->where('user_id', '=', $id)
})->get();
thanks for help.
If you want to run this raw query you can run:
$res = DB::select('
SELECT f2.*
FROM formation f2
WHERE f2.theme_id IN
(SELECT f.theme_id FROM user_formation uf JOIN formation f ON uf.formation_id = f.id WHERE uf.user_id = 2)
AND f2.id NOT IN
(SELECT formation_id FROM user_formation WHERE user_id = 2)');
Or you can rewrite this query in laravel query builder Eloquent ORM:
Formations::query()
->whereIn('formations.theme_id', function($q){
$user_formations_table = (new UserFormation)->getTable();
$formation_table = (new Formation)->getTable();
$q->select('paper_type_id')
->from($user_formations_table)
->join($formation_table, "$user_formations_table.formation_id", '=', "$formation_table.id")
->where("$user_formations_table.user_id", 2);
})->whereNotIn('formations.id', function($q){
$user_formations_table = (new UserFormation)->getTable();
$q->select('formation_id')
->where("$user_formations_table.user_id", 2);
})
->get();
Note that I have used models Formations, UserFormation, Formation Because you have used 3 different tables, you should add this models and specify tables to run ORM query
I advice to run first RAW query if there is no another need to run it with Eloquent
Hope this helps you
First of all, you need to fix your code indentations so you don't confuse yourself. Second, you placed semicolon in the wrong places. Third, you need to pass $id inside function because of the variable scope.
$q = Formation::query()
->whereIn('f2.theme_id', function($r) use ($id) {
$r->select('f.theme_id')->from('user_formation AS uf')
->join('formation', function($join) use ($id) {
$join->on('uf.formation_id', '=', 'f.id')
->where('uf.user_id', '=', $id);
}
);
})
->whereNotIn('f2.id', function($s) use ($id) {
$s->select('formation.id')
->from('user_formation')
->where('user_id', '=', $id);
})->get();
Note : If you are using VSCode, I suggest to use PHP Intelephense as it will help with autocomplete, syntax check, etc.

SQL raw query in laravel query builder

I have a working SQL query.
SELECT stuid,grade,SUM(full_amount) FROM due_payments group by stuid having SUM(full_amount) !=15600
This is working fine in MySQL workbench and phpmyadmin,But i cant seems to get this work in Laravel 5.3
I tried this on Laravel app with no Luck
$someVariable = Input::get(15600);
$results = DB::select( DB::raw("SELECT stuid,grade,SUM(full_amount) FROM due_payments
group by stuid having SUM(full_amount) =:somevariable)", array(
'somevariable' => $someVariable,
)));
Can someone Help me with this.Thank You.
First if all Input::get() doesn't take value as argument but the element name
$someVariable = Input::get(15600);
You can just use $someVariable = 15600;
Then use Query Builder rather than Raw SQL query
$results = DB::table('due_payments')
->select(array('stuid', 'grade', DB::raw('SUM(full_amount)')))
->groupBy('stuid')
->havingRaw('SUM(full_amount) != '.$someVariable)
->get();
Use query builder.
$results = DB::table('due_payments')
->select('stuid', 'grade',DB::raw('SUM(full_amount)'))
->groupBy('stuid')
->havingRaw('SUM(full_amount) != 15600')
->get();

Laravel - How to do a specific query with query builder

I'm using Laravel and have a very specific query that I don't know how to implement with query builder.
The query:
SET #c_num=0;
SELECT *, #c_num:=#c_num+1 AS 'COUNT'
FROM table_name
WHERE USERID = 2
ORDER BY id
Thank you
You should be able to do something like:
DB::statement(DB::raw('SET #c_num = 0'));
$result = DB::table('table_name')
->selectRaw("*, #c_num:=#c_num+1 AS 'COUNT'")
->where('userid', 2)
->orderBy('id')
->get();
$data = DB::table('table_name')
->where('userid',2)
->select('table_name.*',DB::raw('(#c_num:=#c_num+1) Count')
->orderBy('id')
->get();
You can try the following
DB::table('table_name')
->selectRaw("*, #c_num:=IF(#c_num, #c_num+1, 1) as 'COUNT'")
->where('user_id', 2)
->orderBy('id');

Laravel Query Builder WHERE NOT IN

I have the following sql query
SELECT * FROM exams WHERE exams.id NOT IN (SELECT examId FROM testresults)
how can I convert it into Laravel query builder format?
Thanks.
You can use whereNotIn with a closure:
$result = DB::table('exams')->whereNotIn('id', function($q){
$q->select('examId')->from('testresults');
})->get();
with Eloquent :
$result = Exams::whereNotIn('id', function($q){
$q->select('examId')->from('testresults');
})->get();