my query and conversion to Eloquent hi, in laravel5.6 i have a table contacts with several fields, one of them is created_at (timestamp) with format 2018-10-04 14:25:04
if there are 3 contacts the day 2018-10-04, 7 contacts the day 2018-10-05 and only 1 contact the day 2018-10-06
i need a query to know number of contacts by day
in sql the correct query is:
SELECT COUNT('id') as total_contacts, DATE_FORMAT(created_at, '%Y/%m/%d') as day FROM homestead.contacts group by day;
but i dont know how use it with eloquent system ¿?
thank you!
ok i found correct answer, it is:
use Illuminate\Support\Facades\DB;
$leeds = DB::table('contacts')
->select(DB::raw('COUNT(\'id\') as total_contacts, DATE_FORMAT(created_at, \'%Y/%m/%d\') as day'))
->groupby('day')->get();
return view('admin.metric', compact('leeds'));
but i think i am confusig with eloquent and query builder
i think this is the form in query builder format, is not it?
thanks
@ford555 it is the same form. I think you can replace DB::table('contacts')-> with Contacts:: in query builder and get the same result
Contact::select(['id','created_at'])
->get()
->groupBy(function($date) {
return \Carbon\Carbon::parse($date->created_at)->format('Y-m-d');
});
@VAJID - thanks, with my code i can do in the view this:
@foreach($leeds as $leed)
<div>
<span>{{ $leed->total_contacts }}</span>
<span>{{ $leed->day }}</span>
</div>
@endforeach
but i dont know how i can do it with you code.
note: i changed the other message and i wrote the $leeds
@foreach($leeds as $leed_grp)
<div>
<span>{{ count($leed_grp) }}</span>
<span>{{ $leed_grp[0]->created_at }}</span>
</div>
@endforeach
@VAJID - thank you very much!!!, i was confusing about using that kind of array, because if i write dd($leeds) for me it is difficult (i always used var_dump)
Please sign in or create an account to participate in this conversation.