None
None

Reputation: 9247

How to get all records for current year?

How to get all articles for current year?

Articles::all()->where('created_at',$current_year);

Upvotes: 9

Views: 14319

Answers (5)

asim usman
asim usman

Reputation: 19

/*In this code SurveyResult is model name and survey_results is table name and 
date('Y') mean current year. */
/* I hope its helpful for you :) */

SurveyResult::whereYear('survey_results.created_at', date('Y'))->get();

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 178

Get Data via carbon in single line

Articles::whereYear('created_at', Carbon::now()->year)->get();

Upvotes: 3

Ahmed Samy
Ahmed Samy

Reputation: 1

i found this way to collect all years only is good

@if(isset($years) && $years != '')
                    @foreach($years as $yrs)
                        @php($year[] = $yrs->created_at)
                    @endforeach
                    @if(isset($year))
                        @php( $collection = collect($year)->unique()->values()->all())
                            @foreach($collection as $created)
                                @php($year_only[] = $created->format('Y'))
                            @endforeach
                            @php( $collections = collect($year_only)->unique()->values()->all())
                            @foreach($collections as $created_year)
                                @if($created != '')
                                    <div class="lab-item">
                                        <div class="lab-inner" style="border: #ee3725 2px solid;border-radius: 25px;background: bisque;">
                                            <div class="lab-content">
                                                <h4><a href="{{ url('years') }}/{{ $created_year }}"> {{ $created_year }} </a></h4>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                            @endforeach
                    @endif
                @endif

Upvotes: 0

xhulio
xhulio

Reputation: 1103

Try the following query

Articles::whereYear('created_at', '=', Carbon::parse($date)->format('Y'))->get();

Laravel has the helper functions whereDate, whereDay, whereMonth and whereYear to better deal with datetime queries.

Upvotes: 5

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can do this:

Articles::whereBetween('created_at', [
    Carbon::now()->startOfYear(),
    Carbon::now()->endOfYear(),
]);

Another way is to use whereYear() as in @xhulio answer. But I'd recommend you to use this code instead as it's more readable:

Articles::whereYear('created_at', date('Y'))->get();

Upvotes: 26

Related Questions