Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a specific date from an object / collection with eloquent methods like 'where'

I want to implement a chart in my website with chartjs. I am trying that with laravel and I made a function with an Object (Provider) with relations (products, results) and I want to filter it. I just want to have the results of the actual month / actual year. So I tried many things and I can't provide a simple, clean code solution.

I tried following things:

  1. $providerResults->results->where('created_at','2019-01-28 00:00:00') // this is working but I just want to filter with '2019' or '1' for january
  2. $providerResults->results->where('created_at', 'LIKE','%2019%') // not working
  3. $providerResults->results->where('created_at', 'LIKE','%2019%')->get() // not working
  4. $providerResults->results->whereIn('created_at', 2019); // not working

Maybe using filter()?

private function getResultsForChart($objProvider) {

    $providerResults = $objProvider
        ->where('id', AUTH::user()->provider_id)
        ->with('products')
        ->with('results')
        #->whereYear('created_at', 2019)
        #->whereMonth('created_at', 1)
        ->first()
    ;

    $providerResultsForChart = $providerResults->results->whereIn('created_at', 2019);

    dd($providerResultsForChart);

    return $providerResultsForChart;

}

My expected result would be my collection just with the actual month/ actual year instead of everything.

I hope somebody can help me with a hint or a direction which I can use to solve my problem.

Thank you very much in advance!

like image 528
Taranis Avatar asked Nov 20 '25 02:11

Taranis


2 Answers

Try it using the eager loading with conditions like this :

$providerResults = $objProvider
        ->where('id', AUTH::user()->provider_id)
        ->with('products')
        ->with(['results' => function ($query) {
            $query->whereYear('created_at', 2019)
                  ->whereMonth('created_at', 1);
        }])
        ->first();
like image 60
Maraboc Avatar answered Nov 21 '25 15:11

Maraboc


$year = 2019;    
$providerResults = $objProvider
            ->where('id', AUTH::user()->provider_id)
            ->with(['products', 'results' => function ($q) use ($year) {$q->where('created_at', 'LIKE', $year.'%');}])
            ->first();

Try like this. $providerResults->results should return you just results from 2019;

like image 45
Autista_z Avatar answered Nov 21 '25 15:11

Autista_z