I have a problem with my query when I'm trying to group by Date(timestamp) in my laravel project, lets see my code.
RekapController#index
public function index()
{
$absen = Absen::groupBy(raw('DATE(created_at)'))
->orderBy('created_at', 'DESC')
->get();
return view('rekap.index')->with('data', $absen);
}
in my sql syntax is work perfectly
SELECT * FROM absen GROUP BY DATE(created_at) DESC
how can I fix this?
Edit:
The Error is
Call to undefined function App\Http\Controllers\raw()
you can try something like this
$absen = Absen::groupBy(\DB::raw('DATE(created_at)'))
->orderBy('created_at', 'DESC')
->get();
Related
I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();
I'm trying to rewrite this SQL query but I'm stuck at this point
The query is meant to join the projects table to the project_progress table by using a sub-query to only join on the latest entry
SELECT * FROM projects
JOIN project_progress ON project_progress.id =
(
SELECT id FROM project_progress
WHERE project_progress.project_id = projects.id
ORDER BY project_progress.created_at DESC
LIMIT 1
)
WHERE project_progress.next_action_date < NOW()
AND projects.status != 'Complete'
AND projects.member_id = 1
ORDER BY projects.title ASC
To:
$projects = App\Project::where('member_id', 1)
->join('project_progress', function ($join) {
$join->on('project_progress.id', '=', function ($query) {
$query->select('project_progress.id')
->from('project_progress')
->where('project_progress.project_id', 'projects.id')
->orderBy('project_progress.created_at', 'desc')
->limit(1);
});
})
->where('project_progress.next_action_date', '<', Carbon\Carbon::now())
->notCompleted()
->orderBy('projects.project_title', 'asc')
->get();
I think some thing is wrong with this line but I'm not sure how to write it
$join->on('project_progress.id', '=', function ($query) {
ErrorException (E_ERROR) strtolower() expects parameter 1 to be string, object given \vendor\laravel\framework\src\Illuminate\Database\Grammar.php
Use where():
$join->where('project_progress.id', '=', function ($query) {
I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres
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);
IN Custom php code
$select_query = "select * from admin where Stutes = '1' order by ID asc";
How we can embed this code in my this laravel 5 code
public function index()
{
$books=Book::all();
return view('books.index', compact('books'));
}
You can use the Query builder
$admin= DB::tabe('admin')
->select("*")
->where("Stautes",1)
->orderBy("ID", "asc")
->get();
Optimised Query:
Since you are trying to retrieve all rows your query can be likewise:
$admin= DB::table('admin')->where("Status",1) ->orderBy("ID", "asc") ->get();
If you want to retrieve a specific column:
$admin_ids = DB::table('admin')->select('id')->where("Status",1) ->orderBy("ID", "asc") ->get();
Laravel Select docs
Hope this helpful.
In controller
public function index()
{
//$books=Book::all();
$books= DB::table('books')
->select('*')
->where('status', '1')
->orderBy('id', 'asc')
->get();
return view('books.index', compact('books'));
}