ErrorException (E_NOTICE) Undefined index: month

Published 8 months ago by imposition

Hi guys! I'm getting the tittle error with the following code:

BlogController:

    public function index()
    {
      
        
        $blogs = Blog::latest()
        ->filter(request(['month', 'year']))
        ->get();
        




        $archives = Blog::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
            ->groupBy('year', 'month')
            ->orderByRaw('min(created_at) desc')
            ->get()
            ->toArray();






        return view('welcome', compact('blogs', 'archives'));
    }

Blog model:

        public function scopeFilter($query, $filters)
        {
            
            
        if ($month = $filters['month']) {

            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }
        
        if ($year = $filters['year']) {

            $query->whereYear('created_at', $year);
        }

What should i do ?

Best Answer (As Selected By imposition)
Dry7

@imposition try

$blogs = Blog::latest()
        ->filter(request()->only(['month', 'year']))
        ->get();
        if (isset($filters['month'])) {

            $query->whereMonth('created_at', Carbon::parse($filters['month'])->month);
        }
        
        if (isset($filters['year'])) {

            $query->whereYear('created_at', $filters['year']);
        }
Dry7
Dry7
8 months ago (151,680 XP)

@imposition try

$blogs = Blog::latest()
        ->filter(request()->only(['month', 'year']))
        ->get();
        if (isset($filters['month'])) {

            $query->whereMonth('created_at', Carbon::parse($filters['month'])->month);
        }
        
        if (isset($filters['year'])) {

            $query->whereYear('created_at', $filters['year']);
        }
imposition

@Dry7 Okay that worked but now i'm getting an error on another function of the project ._. When i access my home page or the archives on the sidebar menu there are no errors but when i try to access an specific post i get this error!

ErrorException (E_ERROR) Undefined variable: archives

                @foreach ($archives as $stats)
                  <li>
                    
                    <a href="/?month={{ $stats['month'] }}&year={{ $stats['year'] }}">

                    {{ $stats['month'] . ' ' . $stats['year'] }}</a>


                  </li>

                @endforeach
imposition

Added the

        $archives = Blog::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
            ->groupBy('year', 'month')
            ->orderByRaw('min(created_at) desc')
            ->get()
            ->toArray();

To every Controller and it works

Please sign in or create an account to participate in this conversation.